Matthieu Napoli
Matthieu Napoli

Reputation: 49623

PHP namespace organisation, naming

I am facing the following problem :

Where do I put the User base exception class, extended by Forbidden and LoggedOut :

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 !

Upvotes: 2

Views: 888

Answers (2)

KingCrunch
KingCrunch

Reputation: 132011

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".

Upvotes: 3

Sean Huber
Sean Huber

Reputation: 640

Exception\User
Exception\User\Forbidden
Exception\User\LoggedOut

Upvotes: 1

Related Questions