Как Правильно Использовать Команду CLI В Codeigniter 4 Для Выполнения Контроллера

#php #command-line-interface #codeigniter-4

Вопрос:

У меня возникла проблема при использовании команды CLI в codeigniter 4. Я хочу вызвать или выполнить контроллер из интерфейса командной строки codeigniter 4.

У меня есть структура файлов и папок контроллера :

Редактировать :

mywebappappControllersExportAlert.php

И это Код внутри ExportAlert.php :

   <?php

namespace AppControllers;

use CodeIgniterController;


class ExportAlert extends Controller
{   

    function __construct()
    {
            

    }
    

    public function index()
    {   
                
    }



    public function ExportAlert() { 
        if ($this->request->isCLI()) { 
            echo "Ok"; } 
        else { 
            echo "Not allowed"; 
        }                           
    
    }


    
}
 

И Структура Моей Папки :

введите описание изображения здесь

Я пытаюсь выполнить команду CLI :

 E:Codeigniter4mywebapp>php public/index.php ExportAlert ExportAlert
 

И он возвращается :


ОШИБКА: Контроллер 404 или его метод не найден: Экспорталерт::Экспорталерт


Чего мне здесь не хватает ? Как правильно использовать команду CLI для вызова контроллера в codeigniter 4 ?

Спасибо

Ответ №1:

Здесь вам нужно внести несколько изменений: во-первых, это распространяется на контроллер, а не на базовый контроллер.

Поэтому замените инструкцию BaseController use на use CodeIgniterController;

Во — вторых, для этого вам не нужны определенные маршруты. Так что уберите их.

 php index.php ExportAlert ExportAlert
 

должно быть

 php public/index.php ExportAlert ExportAlert
 

Кроме того, вы ничего не определили в теле, поэтому для тестирования попробуйте ввести некоторые данные в CLI, используя метод записи CLI.

Комментарии:

1. Все еще не работает, нужно ли что-то устанавливать ?

2. Можете ли вы загрузить вопрос с обновленным кодом и выполняемыми командами?

3. Не могли бы вы проверить еще раз? Я обновил код. Спасибо

4. Это не сработает. Ваш файл должен находиться в папке Контроллеров, а не во вложенной папке внутри контроллеров. Ваш путь должен быть : mywebappappControllersExportAlert.php

5. Кроме того, для пространства имен отрегулируйте соответствие. Помните, что Codeigniter может обнаруживать контроллеры только непосредственно из папки Контроллеры.

Ответ №2:

Первый:

удалить index.php в URL перейдите по адресу app/config/app.php

публичный $IndexPage = «;

второй:

app/confi/authload.php называю тебя модулями вроде меня

 
<?php

namespace Config;

use CodeIgniterConfigAutoloadConfig;

/**
 * -------------------------------------------------------------------
 * AUTOLOADER CONFIGURATION
 * -------------------------------------------------------------------
 *
 * This file defines the namespaces and class maps so the Autoloader
 * can find the files as needed.
 *
 * NOTE: If you use an identical key in $psr4 or $classmap, then
 * the values in this file will overwrite the framework's values.
 */
class Autoload extends AutoloadConfig
{
    /**
     * -------------------------------------------------------------------
     * Namespaces
     * -------------------------------------------------------------------
     * This maps the locations of any namespaces in your application to
     * their location on the file system. These are used by the autoloader
     * to locate files the first time they have been instantiated.
     *
     * The '/app' and '/system' directories are already mapped for you.
     * you may change the name of the 'App' namespace if you wish,
     * but this should be done prior to creating any namespaced classes,
     * else you will need to modify all of those classes for this to work.
     *
     * Prototype:
     *```
     *   $psr4 = [
     *       'CodeIgniter' => SYSTEMPATH,
     *       'App'           => APPPATH
     *   ];
     *```
     * @var array<string, string>
     */
    public $psr4 = [
        APP_NAMESPACE => APPPATH, // For custom app namespace
        'Config' => APPPATH . 'Config',
        'ModulesShared' => ROOTPATH . 'module/shared',
        'ModulesCommon' => ROOTPATH . 'module/common',
        'ModulesAuth' => ROOTPATH . 'module/auth',
        'ModulesHome' => ROOTPATH . 'module/home',
        'ModulesPayment' => ROOTPATH . 'module/payment',
    ];

    /**
     * -------------------------------------------------------------------
     * Class Map
     * -------------------------------------------------------------------
     * The class map provides a map of class names and their exact
     * location on the drive. Classes loaded in this manner will have
     * slightly faster performance because they will not have to be
     * searched for within one or more directories as they would if they
     * were being autoloaded through a namespace.
     *
     * Prototype:
     *```
     *   $classmap = [
     *       'MyClass'   => '/path/to/class/file.php'
     *   ];
     *```
     * @var array<string, string>
     */
    public $classmap = [];

    /**
     * -------------------------------------------------------------------
     * Files
     * -------------------------------------------------------------------
     * The files array provides a list of paths to __non-class__ files
     * that will be autoloaded. This can be useful for bootstrap operations
     * or for loading functions.
     *
     * Prototype:
     * ```
     *      $files = [
     *           '/path/to/my/file.php',
     *    ];
     * ```
     * @var array<int, string>
     */
    public $files = [];
}