Slim 3自动装带器 [英] Slim 3 autoloader

查看:98
本文介绍了Slim 3自动装带器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是苗条框架的新手,无法弄清楚如何使用自动加载器自动加载我的类.

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 App\Model;
  • 在depedencies.php中添加了以下内容:
$container['App\Model\Client'] = function ($c) {
    return new App\Model\Client();
};

和routes.php:

and routes.php:

$app->get('/client/ping/{id}',  function ($request, $response, $args)  {
    $container = $this->getContainer();
    $client=$container['App\Model\Client']; //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 \Slim\App();
$myClass = new \My\Namespace\MyClass();

运行composer update后,composer将注册您自己的名称空间并为您自动加载它们.

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

这篇关于Slim 3自动装带器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆