Slim 3 autoloader

两盒软妹~` 提交于 2019-11-30 04:56:40

问题


I'm new to slim framework, and can't figure out how to use the autoloader to autoload my classes.

I created a app/models/myclass.php but of course when I try to use it I get a class not found. I'm not sure which is the right way to autoload classes, or the naming convensions I should use. Should I do it via the composer.json somehow? I'm searching the net for several hours without any solid answer on that.

UPDATE:

Managed to do it like that:

  • added model in : app/src/Model/Client.php
  • added namespace App\Model; in Client.php
  • added the following in depedencies.php:
$container['App\Model\Client'] = function ($c) {
    return new App\Model\Client();
};

and routes.php:

$app->get('/client/ping/{id}',  function ($request, $response, $args)  {
    $container = $this->getContainer();
    $client=$container['App\Model\Client']; //instantiates a new Client
    ...
    ...
}

回答1:


For autoloading of own classes you should use Composer by adding some options to your composer.json:

{
    "require": {
        "slim/slim": "^3.9"
    },
    "autoload": {
        "psr-4": {
            "My\\Namespace\\": "src/"
        }
    }
}
// index.php
require 'vendor/autoload.php';

$app = new \Slim\App();
$myClass = new \My\Namespace\MyClass();

After running composer update composer will register your own namespaces and will autoload them for you.




回答2:


Add this in composer.json file Where app1 is the name of the folder you want to Autoload.

"autoload": {
    "psr-4":{
        "app1\\": "anything"
    }
}

After doing this run this in cmd (via composer)

composer dump-autoload -o


来源:https://stackoverflow.com/questions/31500702/slim-3-autoloader

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!