【问题标题】:What's the correct method for using Traits and Namespaces for CakePHP 2?为 CakePHP 2 使用 Traits 和 Namespaces 的正确方法是什么?
【发布时间】:2014-01-28 00:50:18
【问题描述】:

我正在使用 CakePHP 2.4.5 和 PHP 5.5,并希望使用 trait。

我在 Utility/VariablesTrait.php 中有一个名为 VariablesTrait 的特征。

为了利用命名空间,我给它一个命名空间App\Utility\VariablesTrait,因为Utility\VariablesTrait 似乎有点过于全球化,而前者在CakePHP 3 中会更好地工作。

在我想使用它的班级中,我在班级中有use App\Utility\VariablesTrait; 语句。对于备份,我还在文件顶部有一个App::uses('VariablesTrait', 'Utility'); 语句。我不确定在寻找特征时是否使用了 SPL 自动加载器,这就是我首先要寻找命名空间的原因。

小问题是应用程序目录是app,由于目录结构应该匹配命名空间(我认为),我将其重命名为App。但是,CakeRequest::_base() 硬编码app,因此确定控制器并不能很好地工作。

所以,我正在尝试确定这是否是 CakePHP 错误,或者是否有更合适的方式在 CakePHP 2 中使用特征。

【问题讨论】:

    标签: php cakephp namespaces traits


    【解决方案1】:

    一个简单的方法是使用 CakePHP build 添加你的包文件夹,然后通过你选择的名称来引用它,例如:

    将此添加到bootstrap.php

    /**
     * Add New Package Locations
     */
    App::build(['Controller/Trait' => [APP . 'Controller' . DS . 'Trait' . DS]], App::REGISTER);
    

    然后就用它来引入你的特质:

    App::uses('TestTrait', 'Controller/Trait');
    

    您还可以一次添加多个包文件夹,这样您显然可以执行以下操作:

    /**
     * Add New Package Locations
     */
    App::build(['All/Trait' => [
        APP . 'Controller' . DS . 'Trait' . DS,
        APP . 'Model' . DS . 'Trait' . DS,
        APP . 'Lib' . DS . 'Trait' . DS
    ]], App::REGISTER);
    

    【讨论】:

    • 嗨,命名空间中 PHP 的无效使用词。示例:命名空间 Project\Classes\Function; // 导致解析错误 namespace Project\Abstract\Factory; // 导致解析错误 namespace App\Model\Entity\Trait\; // 导致解析错误 有效例如是 App\Model\Entity\AllTrait\
    【解决方案2】:

    我的理解是 CakePHP 不会自动加载。我使用以下内容来导入命名空间类:

    spl_autoload_register(
    function ( $class )
    {
        foreach ( App::path('Vendor', 'MyFile') as $base )
        {
            $path = $base . str_replace('\\', DS, $class) . '.php';
            if ( file_exists($path) )
            {
                return include $path;
            }
        }
    }
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-17
      • 2015-03-31
      • 2019-05-17
      • 2014-12-08
      • 1970-01-01
      • 2023-03-15
      • 2011-11-11
      • 2015-03-01
      相关资源
      最近更新 更多