如何在 Laravel 中命名模型以免与现有类发生冲突?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16116378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I namespace a model in Laravel so as not to clash with an existing class?
提问by Dwight
In Laravel 4 I want to use a model that represents an Event
coming from my database. Thus, in app/models
I have my Event
model that extends Eloquent.
在 Laravel 4 中,我想使用一个代表Event
来自我的数据库的模型。因此,在app/models
我的Event
模型中,我扩展了 Eloquent。
However, Laravel 4 already has an Event
class which is used to manage events within the application lifecycle.
但是,Laravel 4 已经有一个Event
类用于管理应用程序生命周期内的事件。
What I want to know is, how can I properly namespace my Event
model and access it in a way that will not clash with the existing Event
class.
我想知道的是,如何正确命名Event
模型并以不与现有Event
类冲突的方式访问它。
回答by Jason Lewis
You just need to apply a namespace to it as you normally would. So, for example.
您只需要像往常一样为其应用命名空间。所以,例如。
<?php namespace Models;
use Eloquent;
class Event extends Eloquent {
}
You should then correctly setup your composer.json
so that it loads your models. You could use classmap
or psr-0
for this, depending on whether or not you're following PSR-0 with your directory structure.
然后你应该正确设置你的,composer.json
以便它加载你的模型。您可以为此使用classmap
或psr-0
,具体取决于您的目录结构是否遵循 PSR-0。
I'm pretty sure the models
directory is already mapped.
我很确定该models
目录已经映射。
Edit
As mentioned in the comments you must run composer dump-autoload
.
编辑
如评论中所述,您必须运行composer dump-autoload
.
回答by Zulqurnain abbas
As much i have research about using namespaces, because i want to use those inside the PHPDocumentar, its not possible to add twice the namespaces, as laravel already adds those for you, if we understand the basic problem, why we use namespaces
我对使用命名空间有很多研究,因为我想在 PHPDocumentar 中使用那些,不可能添加两倍的命名空间,因为 laravel 已经为你添加了这些,如果我们理解基本问题,为什么我们使用命名空间
1 - many libraries uses same class name, so we use namespaces to differentiate that.
1 - 许多库使用相同的类名,所以我们使用命名空间来区分。
2 - if you want to use namespaces then you should be out of the scope of the app, means is the vendor folder for you to this kind of stuff.
2 - 如果您想使用命名空间,那么您应该超出应用程序的范围,这意味着供应商文件夹适合您进行此类操作。
Enjoy
享受