PHP命名空间组织、命名
我面临以下问题:
我有一个命名空间
Exception\*
, 其中包含几种类型 异常。我有一个命名空间
Exception\User\*
,其中包含 特定类型的例外 (Forbidden
、LoggedOut
...)。
我将 User
基本异常类放在哪里,由 Forbidden
和 LoggedOut
扩展:
Exception\User
,即在Exception\*
命名空间中(更好的全名)?Exception\User\User
,即在Exception\User\*
命名空间中(更一致)?Exception\User\Exception
,即我将其重命名为Exception\User\*
命名空间的“基本”异常(奇怪)?
注意:User
异常类不是抽象的。
精度:我使用了一个有例外的示例,这只是一个示例。我真的很想知道在名称空间树中放置/如何命名基类的位置。
如果您能帮助我,谢谢!
I am facing the following problem :
I have a namespace
Exception\*
,
which contains several types of
exceptions.I have a namespace
Exception\User\*
, which contains a
specific kind of exceptions
(Forbidden
,LoggedOut
...).
Where do I put the User
base exception class, extended by Forbidden
and LoggedOut
:
Exception\User
, i.e. in theException\*
namespace (better full name) ?Exception\User\User
, i.e. in theException\User\*
namespace (more consistent) ?Exception\User\Exception
, i.e. I rename it to be the "base" exception of theException\User\*
namespace (weird) ?
NB : the User
exception class is not abstract.
Precision : I've used an example with exceptions, this is just an example. I am really wondering about where to put/how to name a base class in a namespace tree.
Thanks if you can help me !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如何设计代码完全取决于您。然而,有些人已经考虑过这一点并定义了 PSR-0 标准。无论如何,你的概念似乎不太有用。如果命名空间
\My\Space
中出现问题(我认为),每个人都会期望该命名空间出现异常。如果原因和异常本身之间存在逻辑联系,则设计相应的 try-catch 子句会更容易。更新(反映问题中的精度):
我认为,有(可以说)2.5种方法;)您可以将基类放在通常使用/实现/扩展的命名空间中,例如
*\Filter \FilterInterface
和*\Filter\ConcreteFilter
。另一种解决方案是将其提高一级(*\Filter
),并在接口/基类之后命名子命名空间,或者只是将其命名为其他名称(这是一半的解决方案)。我更喜欢最后一个,例如接口*\Filter
和具体类*\filters\SomeFilter
(是的,我的命名空间是小写的;))。要点是,你要坚持自己的决定。不要混淆多种“风格”。
How you design your code is really up to you. However, there were some guys, who already thought about this and defined the PSR-0 standard. At all your concept seems not very usable. If something went wrong within the namespace
\My\Space
(I think) everybody would expect an exception from this namespace. Its easier to design the correspondingtry-catch
-clauses, if there is a logical link between the cause and the exception itself.Update (reflecting the precision in the question):
I think, there are (lets say) 2.5 ways ;) You can put the base class in the namespace, where it is usually use/implemented/extended, e.g.
*\Filter\FilterInterface
and*\Filter\ConcreteFilter
. The other solution is to put it one level up (*\Filter
) and either name the sub-namespace after the interface/base-class, or just name it something else (thats the half solution). I prefer the last one, for example interface*\Filter
and a concrete class*\filters\SomeFilter
(and yes, my namespaces are in lowercase ;)).The main point is, that you stay with your decision. Do not mix up multiple "styles".