问题
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:
Include in composer.json this:
"autoload": { "classmap": [ "app/traits" ] }
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