douyou8266 2014-05-13 22:00
浏览 30
已采纳

模型失败的Laravel外观:无法重新声明类内容

I want to add a Facade to my model named Content. But I always get the error Cannot redeclare class Content. Is that because the model is already loaded via the autoload? How can I fix this?

I appreciate you help, thanks.

This is how my composer file looks like

"autoload": {
    "psr-4": {
        "App\\": "app/"
    },
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/database/migrations",
        "app/database/seeds",
        "app/tests/TestCase.php",
        "app/Serviceproviders"
    ]
},

And this is how my Serviceprovider looks like.

<?php namespace App\Serviceproviders;

use Illuminate\Support\ServiceProvider;

class FormandsystemServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->bind('content', function()
        {
            return new \App\models\Content;
        });

          $this->app->booting(function()
          {
            $loader = \Illuminate\Foundation\AliasLoader::getInstance();
            $loader->alias('Content', '\App\Facades\Content');
          });
    }

}

My Facade looks like this.

<? namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class Content extends Facade {

    protected static function getFacadeAccessor() { return 'content'; }
}

展开全部

  • 写回答

1条回答 默认 最新

  • douwu5009 2014-05-14 22:42
    关注

    Okay, I got it, the Problem seems to be that both facade and model are named the same, which is unexpected, because it works just like this with packages but I guess this might be because of those not being autoloaded?

    Anyway, my "solution" is the following:

    1. Removing "app/Serviceproviders" from composer.json as I am loading this via app.php anyway.

    2. Renaming my mode ContentModel and the file ContentModel.php because I want my Facade to be Content. This lives in the standard model folder.

    3. My facade is still named Content and the file is content.php which lives in app/Facades

    4. This is my Serviceprovider which is loaded using the app.php file

    use Illuminate\Support\ServiceProvider;

    class FormandsystemServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->bind('content', function()
        {
            return new \App\models\ContentModel;
        });
    
          $this->app->booting(function()
          {
            $loader = \Illuminate\Foundation\AliasLoader::getInstance();
            $loader->alias('Content', '\App\Facades\Content');
          });
        }
    }
    

    This works just fine I can now call Content::getFirst() which is a method from my content model.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部