Slim 3 自动装载机 [英] Slim 3 autoloader
问题描述
我是瘦框架的新手,不知道如何使用自动加载器来自动加载我的类.
I'm new to slim framework, and can't figure out how to use the autoloader to autoload my classes.
我创建了一个 app/models/myclass.php
但是当然当我尝试使用它时我找不到一个类.我不确定哪种是自动加载类的正确方法,或者我应该使用的命名约定.我应该通过 composer.json 以某种方式做到这一点吗?我在网上搜索了几个小时,但没有任何可靠的答案.
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.
更新:
设法做到了:
- 在:app/src/Model/Client.php 中添加模型
- 在 Client.php 中添加了
namespace AppModel;
- 在 depedencies.php 中添加了以下内容:
$container['AppModelClient'] = function ($c) {
return new AppModelClient();
};
和routes.php:
and routes.php:
$app->get('/client/ping/{id}', function ($request, $response, $args) {
$container = $this->getContainer();
$client=$container['AppModelClient']; //instantiates a new Client
...
...
}
推荐答案
为了自动加载自己的类,你应该使用 Composer
通过向你的 composer.json
添加一些选项:
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 SlimApp();
$myClass = new MyNamespaceMyClass();
运行 composer update
后,composer 将注册您自己的命名空间并为您自动加载它们.
After running composer update
composer will register your own namespaces and will autoload them for you.
这篇关于Slim 3 自动装载机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!