laravel 4 trait autoloading in models

半腔热情 提交于 2019-12-24 07:07:08

问题


OK, I am struggling for over 2 hours now...

It must be one of the "oh god, it was that obvious" times where you are so tired and you cannot see the solution...

I want to extend the eloquentmodel to include a trait.

so my class looks like

<?php 
class Note extends Eloquent{
  use \Admin\GreatTrait;

  ...
}

and I created the app/Traits/Admin directory structure and there I created the file named GreatTrait.php with the following contents:

<?php namespace Admin;

trait GreatTrait{
  ...
}

and of cource I edited the start/global.php to include the dir to the ClassLoader like so

ClassLoader::addDirectories(array(
    app_path().'/commands',
    ... more ...
    app_path().'/traits',
    app_path().'/traits/Admin',
));

and I get the following error...

Symfony \ Component \ Debug \ Exception \ FatalErrorException

Trait 'Admin\GreatTrait' not found

Anything to suggest?


回答1:


Following your code, i made it work with next changes:

  1. Include in composer.json this:

    "autoload": {
        "classmap": [
            "app/traits"
        ] 
    }
  2. Include in model after class declaration (just trait name, without directory):

    php 
    class Note extends Eloquent {
        use \GreatTrait;
        ...
    }
    ?>



回答2:


I had some issues with autoloading in global.php, you can do the same using copmposer.json:

Add the path to autoload array in composer.json

"autoload": {
                "classmap": [
                        "app/traits"
                ]
        },

Run composer dump-autoload

In app/traits path you should have the admin folder app/traits/admin with a class setting up the namespace Admin.

<?php
namespace Admin
class GreatTrait { ... }

Then you can use

<?php 
use \Admin\GreatTrait;
class Note extends Eloquent{

  ...
}


来源:https://stackoverflow.com/questions/22103143/laravel-4-trait-autoloading-in-models

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