Question

I'm using CakePHP 2.4.5 and PHP 5.5, and would like to use a trait.

I have a trait in Utility/VariablesTrait.php called VariablesTrait.

To take advantage of namespaces, I've given it a namespace of App\Utility\VariablesTrait, since Utility\VariablesTrait seems a bit too global, and the former would work better with CakePHP 3.

In my class that I want to use it in, I have the use App\Utility\VariablesTrait; statement in the class. For backup, I also have a App::uses('VariablesTrait', 'Utility'); statement at the top of the file. I'm not sure if the SPL autoloader is used when looking for traits, which is why I was going for namespaces in the first place.

The small issue is that the app directory is app, and since directory structures should match namespaces (I think), I renamed it to App. However, CakeRequest::_base() hardcodes app, so determining the controller doesn't work so well.

So, I'm trying to determine if that's a CakePHP bug, or if there is a more appropriate way of using traits in CakePHP 2.

Was it helpful?

Solution

An easy way to do this is to use CakePHP build to add your package folder, then just refer to it by the name you chose so for example:

Add this to bootstrap.php:

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

Then just use this to pull in your traits:

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

You can also add multiple package folders at a time so you can apparently do something like this:

/**
 * 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);

OTHER TIPS

My understanding is that CakePHP doesn't autoload. I use the following for importing namespaced classes:

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;
        }
    }
}
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top