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开发者_Python百科\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 !
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 corresponding try-catch
-clauses, if there is a logical link between the cause and the exception itself.
try {
$x = new \My\Space\Class;
$x->doSomething();
} catch (\My\Space\SomethingWentWrongException $e) {
// something went wrong
} catch (\My\Space\Exception $e) {
// something unexpected from this namespace went wrong
}
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".
Exception\User
Exception\User\Forbidden
Exception\User\LoggedOut
精彩评论