Codeigniter 4 Restful API 只有默认控制器,路由不起作用

Code Igniter 4 Restful API only default controller, routes not work

我尝试在 Apache2 上使用 Code Igniter 4 创建 restful api。如果我打开 http://<my-ip:port>,它会显示欢迎信息。然后我创建了 Account.php 控制器以从数据库中获取帐户列表。

<?php namespace App\Controllers;
 
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\AccountModel;
 
class Account extends ResourceController
{
    use ResponseTrait;
    public function index()
    {
        $model = new AccountModel();
        $data = $model->findAll();
        return $this->respond($data, 200);
    }
 
    public function show($id = null)
    {
        $model = new AccountModel();
        $data = $model->getWhere(['account_id' => $id])->getResult();
        if($data){
            return $this->respond($data);
        }else{
            return $this->failNotFound('No Data Found with id '.$id);
        }
    }
}

AccountModel.php

<?php namespace App\Models;
 
use CodeIgniter\Model;
 
class AccountModel extends Model
{
    protected $table = 'account';
    protected $primaryKey = 'id';
    protected $allowedFields = ['account_id','name'];
}

我设置了CorsFilters

这是我的路线

<?php

namespace Config;

$routes = Services::routes();

if (file_exists(SYSTEMPATH . 'Config/Routes.php')) {
    require SYSTEMPATH . 'Config/Routes.php';
}

$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('Home');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
$routes->setAutoRoute(true);

//$routes->get('/','Home::index');
$routes->resource('account');

if (file_exists(APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php')) {
    require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php';
}

http://my-ip:port 显示欢迎信息。但是如果我使用邮递员打开 http://<my-ip:port/account> 我得到错误

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
<hr>
<address>Apache/2.4.46 (Ubuntu) Server at <my-ip> Port 80</address>
</body></html>

并且我将 Account 设置为默认控制器 $routes->setDefaultController('Account'); 如果我打开 http://<my-ip:port> 我会得到帐户列表。我错过了一些设置吗?如果我打开http://<my-ip:port/account>和其他

,我想获取帐户列表

如果尝试 http:// more infos

使用 restful ctl ci4

查看我的代码的最佳方式

第一次溃败


<?php

/*
 * Core Auth  routes file.
 */

$routes->group('api', ['namespace' => 'Modules\Auth\Controllers'], function ($routes) {

    $routes->resource('group', ['filter' => 'authJwt']);
    $routes->resource('permission', ['filter' => 'authJwt']);
    $routes->resource('groupPermission', ['filter' => 'authJwt']);
    $routes->resource('userPermission', ['filter' => 'authJwt']);

    $routes->group('auth', function ($routes) {

        $routes->post('signin-jwt', 'Auth::signInJwt', ['filter' => 'isSignIn']);
        $routes->post('signin', 'Auth::signIn', ['filter' => 'isSignIn']);
        $routes->get('signout', 'Auth::signOut', ['filter' => 'authJwt']);
        $routes->get('is-signin', 'Auth::isSignIn',['filter' => 'authJwt']);


        $routes->post('signup', 'Auth::signUp', ['filter' => 'isSignIn']);
        $routes->post('forgot', 'Auth::forgot', ['filter' => 'isSignIn']);

        $routes->post('reset-password-email', 'Auth::resetPasswordViaEmail', ['filter' => 'isSignIn']);
        $routes->post('reset-password-sms', 'Auth::resetPasswordViaSms', ['filter' => 'isSignIn']);

        $routes->post('activate-account-email', 'Auth::activateAccountViaEmail', ['filter' => 'isSignIn']);
        $routes->post('send-activate-email', 'Auth::sendActivateCodeViaEmail', ['filter' => 'isSignIn']);

        $routes->post('activate-account-sms', 'Auth::activateAccountViaSms', ['filter' => 'isSignIn']);
        $routes->post('send-activate-sms', 'Auth::sendActivateCodeViaSms', ['filter' => 'isSignIn']);

    });

});



第二个api ctl

<?php

namespace Modules\Shared\Controllers;

/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 *
 * @package CodeIgniter
 */


use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
use Modules\Auth\Config\Services;
use Myth\Auth\AuthTrait;
use Psr\Log\LoggerInterface;
use  Modules\Shared\Interfaces\UrlAggregationInterface;
use  Modules\Shared\Libraries\UrlAggregation;

class ApiController extends ResourceController
{
    use AuthTrait;

    protected $format = "";
    public object $userObject;
    public UrlAggregationInterface $urlAggregation;

    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    protected $helpers = [
        'cookie',
        'url',
        'from',
        'filesystem',
        'text',
        'shared'
    ];

    /**
     * Constructor.
     *
     * @param RequestInterface $request
     * @param ResponseInterface $response
     * @param LoggerInterface $logger
     */


    /**
     * @var string
     * Holds the session instance
     */
    protected $session;

    public function __construct()
    {

        $this->userObject = (object)[];
    }

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);


        $this->urlAggregation = new UrlAggregation($request);

        $requestWithUser = Services::requestWithUser();
        $this->userObject = $requestWithUser->getUser();

    }

}



第三个 ctl

<?php namespace Modules\Auth\Controllers;


use Modules\Auth\Config\Services;
use Modules\Auth\Entities\GroupEntity;
use CodeIgniter\HTTP\ResponseInterface;
use Modules\Shared\Controllers\ApiController;

class  Group extends ApiController
{
    /**
     * index function
     * @method : GET
     */
    public function index()
    {


        $groupEntity = new GroupEntity();

        $this->urlAggregation->dataMap($groupEntity->getDataMap());


        $groupService = Services::groupService();
        $findAllData = $groupService->index($this->urlAggregation);

        return $this->respond([
            'data' => $findAllData['data'],
            'pager' => $findAllData['pager']
        ], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));


    }

    /**
     * show function
     * @method : GET with params ID
     */
    public function show($id = null)
    {
        $groupService = Services::groupService();
        $findOneData = $groupService->show($id);

        return $this->respond([
            'data' => $findOneData['data'],
            'pager' => $findOneData['pager']
        ], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));


    }

    public function create()
    {


        $rules = [
            'name' => 'required|min_length[3]|max_length[255]|is_unique[auth_groups.name]',
            'description' => 'required|min_length[3]|max_length[255]',
        ];

        if (!$this->validate($rules)) {

            return $this->respond([
                'error' => $this->validator->getErrors(),
                
            ], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));

        }


        $groupEntity = new GroupEntity((array)$this->request->getVar());

        $groupService = Services::groupService();
        $groupService->create($groupEntity);


        return $this->respond([
            'data' => ''
        ], ResponseInterface::HTTP_CREATED, lang('Shared.api.save'));


    }

    /**
     * update function
     * @method : PUT or PATCH
     */
    public function update($id = null)
    {


        //get request from Vue Js

        //get request from Vue Js
        $json = $this->request->getJSON();
        if (!isset($id)) {
            $id = $json->id;
        }


        $rules = [
            'name' => 'if_exist|required|min_length[3]|max_length[255]',
            'description' => 'required|min_length[3]|max_length[255]',
        ];

        if (!$this->validate($rules)) {
            return $this->respond([
                'error' => $this->validator->getErrors(),
                
            ], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));

        }


        $groupEntity = new GroupEntity((array)$this->request->getVar());

        $groupService = Services::groupService();
        $groupService->update($id, $groupEntity);


        return $this->respond([
        ], ResponseInterface::HTTP_OK, lang('Shared.api.update'));


    }

    /**
     * edit function
     * @method : DELETE with params ID
     */
    public function delete($id = null)
    {

        $groupService = Services::groupService();
        $groupService->delete($id);


        return $this->respond([
        ], ResponseInterface::HTTP_OK, lang('Shared.api.remove'));


    }


}

entitiy

第四次服务

<?php namespace Modules\Auth\Config;


use CodeIgniter\HTTP\UserAgent;
use Config\App;
use Config\Services as AppServices;
use Config\Services as BaseService;
use Modules\Auth\Libraries\RequestWithUser;
use Modules\Auth\Services\AuthService;
use Modules\Auth\Services\GroupsPermissionService;
use Modules\Auth\Services\PermissionService;
use Modules\Auth\Services\RoleRouteService;
use Modules\Auth\Services\GroupService;
use Modules\Auth\Services\UsersPermissionService;

class Services extends BaseService
{
    //--------------------------------------------------------------------

    /**
     * The Request class models an HTTP request.
     *
     * @param App|null $config
     * @param boolean $getShared
     *
     * @return RequestWithUser
     */
    public static function requestWithUser(App $config = null, bool $getShared = true)
    {
        if ($getShared) {
            return static::getSharedInstance('requestWithUser', $config);
        }

        $config = $config ?? config('App');;
        return new RequestWithUser(
            $config,
            AppServices::uri(),
            'php://input',
            new UserAgent()
        );
    }

    //--------------------------------------------------------------------


    public static function roleRoute($getShared = true)
    {
        if ($getShared) {
            return static::getSharedInstance('roleRoute');
        }

        return new RoleRouteService();
    }
//--------------------------------------------------------------------

    public static function authService($getShared = false)
    {
        if (!$getShared) {
            return new AuthService();
        }
        return static::getSharedInstance('authService');

    }
//--------------------------------------------------------------------

    public static function groupService($getShared = false)
    {
        if (!$getShared) {


            return new GroupService();
        }

        return static::getSharedInstance('groupService');
    }
//--------------------------------------------------------------------

    public static function permissionService($getShared = false)
    {
        if (!$getShared) {


            return new PermissionService();
        }

        return static::getSharedInstance('permissionService');
    }
//--------------------------------------------------------------------

    public static function groupsPermissionService($getShared = false)
    {
        if (!$getShared) {


            return new GroupsPermissionService();
        }

        return static::getSharedInstance('groupsPermissionService');
    }
//--------------------------------------------------------------------

    public static function userPermissionService($getShared = false)
    {
        if (!$getShared) {


            return new UsersPermissionService();
        }

        return static::getSharedInstance('usersPermissionService');
    }

//--------------------------------------------------------------------

}





<?php namespace Modules\Auth\Entities;

use \CodeIgniter\Entity;
use CodeIgniter\I18n\Time;

class  GroupEntity extends Entity
{

   protected $id;
   protected $name;
   protected $description;


    //check type of data

//    protected $casts = ['
//    is_flag' => 'boolean'];

    protected $attributes = [
        'id' => null,
        'name' => null,
        'description' => null,

    ];
    protected $datamap = [
    ];

    protected $dates = [];

    protected $casts = [];

    protected $permissions = [];

    protected $roles = [];




}



型号

<?php namespace Myth\Auth\Authorization;

use CodeIgniter\Model;
use Modules\Auth\Entities\GroupEntity;
use Modules\Shared\Models\Aggregation;

class GroupModel extends Aggregation
{
    protected $table = 'auth_groups';
    protected $primaryKey = 'id';
    protected $returnType = GroupEntity::class;

    protected $allowedFields = [
        'name', 'description'
    ];

    protected $useTimestamps = false;

    protected $validationRules = [
        'name' => 'required|max_length[255]|is_unique[auth_groups.name,name,{name}]',
        'description' => 'max_length[255]',
    ];
    protected $validationMessages = [];
    protected $skipValidation = false;

    //--------------------------------------------------------------------
    // Users
    //--------------------------------------------------------------------

    /**
     * Adds a single user to a single group.
     *
     * @param int $userId
     * @param int $groupId
     *
     * @return bool
     */
    public function addUserToGroup(int $userId, int $groupId)
    {    
        cache()->delete("{$groupId}_users");
        cache()->delete("{$userId}_groups");
        cache()->delete("{$userId}_permissions");

        $data = [
            'user_id'  => (int) $userId,
            'group_id' => (int) $groupId
        ];

        return (bool) $this->db->table('auth_groups_users')->insert($data);
    }

    /**
     * Removes a single user from a single group.
     *
     * @param int $userId
     * @param int|string $groupId
     *
     * @return bool
     */
    public function removeUserFromGroup(int $userId, $groupId)
    {
        cache()->delete("{$groupId}_users");
        cache()->delete("{$userId}_groups");
        cache()->delete("{$userId}_permissions");

        return $this->db->table('auth_groups_users')
            ->where([
                'user_id'  => $userId,
                'group_id' => (int) $groupId
            ])->delete();
    }

    /**
     * Removes a single user from all groups.
     *
     * @param int $userId
     *
     * @return bool
     */
    public function removeUserFromAllGroups(int $userId)
    {
        cache()->delete("{$userId}_groups");
        cache()->delete("{$userId}_permissions");

        return $this->db->table('auth_groups_users')
            ->where('user_id', (int)$userId)
            ->delete();
    }

    /**
     * Returns an array of all groups that a user is a member of.
     *
     * @param int $userId
     *
     * @return array
     */
    public function getGroupsForUser(int $userId)
    {
        if (null === $found = cache("{$userId}_groups"))
        {
            $found = $this->builder()
                ->select('auth_groups_users.*, auth_groups.name, auth_groups.description')
                ->join('auth_groups_users', 'auth_groups_users.group_id = auth_groups.id', 'left')
                ->where('user_id', $userId)
                ->get()->getResultArray();

            cache()->save("{$userId}_groups", $found, 300);
        }

        return $found;
    }

    /**
     * Returns an array of all users that are members of a group.
     *
     * @param int $groupId
     *
     * @return array
     */
    public function getUsersForGroup(int $groupId)
    {
        if (null === $found = cache("{$groupId}_users"))
        {
            $found = $this->builder()
                ->select('auth_groups_users.*, users.*')
                ->join('auth_groups_users', 'auth_groups_users.group_id = auth_groups.id', 'left')
                ->join('users', 'auth_groups_users.user_id = users.id', 'left')
                ->where('auth_groups.id', $groupId)
                ->get()->getResultArray();

            cache()->save("{$groupId}_users", $found, 300);
        }

        return $found;
    }

    //--------------------------------------------------------------------
    // Permissions
    //--------------------------------------------------------------------

    /**
     * Gets all permissions for a group in a way that can be
     * easily used to check against:
     *
     * [
     *  id => name,
     *  id => name
     * ]
     *
     * @param int $groupId
     *
     * @return array
     */
    public function getPermissionsForGroup(int $groupId): array
    {
        $permissionModel = model(PermissionModel::class);
        $fromGroup = $permissionModel
            ->select('auth_permissions.*')
            ->join('auth_groups_permissions', 'auth_groups_permissions.permission_id = auth_permissions.id', 'inner')
            ->where('group_id', $groupId)
            ->findAll();

        $found = [];
        foreach ($fromGroup as $permission)
        {
            $found[$permission['id']] = $permission;
        }

        return $found;
    }

    /**
     * Add a single permission to a single group, by IDs.
     *
     * @param int $permissionId
     * @param int $groupId
     *
     * @return mixed
     */
    public function addPermissionToGroup(int $permissionId, int $groupId)
    {
        $data = [
            'permission_id' => (int)$permissionId,
            'group_id'      => (int)$groupId
        ];

        return $this->db->table('auth_groups_permissions')->insert($data);
    }

    //--------------------------------------------------------------------


    /**
     * Removes a single permission from a single group.
     *
     * @param int $permissionId
     * @param int $groupId
     *
     * @return mixed
     */
    public function removePermissionFromGroup(int $permissionId, int $groupId)
    {
        return $this->db->table('auth_groups_permissions')
            ->where([
                'permission_id' => $permissionId,
                'group_id'      => $groupId
            ])->delete();
    }

    //--------------------------------------------------------------------

    /**
     * Removes a single permission from all groups.
     *
     * @param int $permissionId
     *
     * @return mixed
     */
    public function removePermissionFromAllGroups(int $permissionId)
    {
        return $this->db->table('auth_groups_permissions')
            ->where('permission_id', $permissionId)
            ->delete();
    }
}