Search code examples
phpoopdesign-patternsorganizationcode-organization

best practice for organizing your class/subclass files


This is more of a preference question but I want to know what do people prefer when organizing their application's directory tree for managing classes, and subclasses.

given the file name = class name

A - subclassing within folders

Foo.php

Foo/Bar.php // extends Foo

Foo/Bar/Baz.php // extends Foo\Bar

Real World Example

Post.php

Post/Media.php - extends Post

Post/Media/Image.php - extends Post\Media

Post/Media/Audio.php - extends Post\Media

B - subclassing within the class name

Foo.php

BarFoo.php

BazBarFoo.php

Real World Example

Post.php

MediaPost.php - extends Post

ImageMediaPost.php - extends MediaPost

AudioMediaPost.php - extends MediaPost


Please share your thoughts.


Solution

  • Generally speaking, subclassing is an anti-pattern. It tightly couples classes together, and can result in some hard-to-maintain code. It's much more appropriate to have clean interfaces with inversion of control. You'll then end up with small components that do one job, and one only. I'm going to answer your question though, but I needed to tell you why I think this:

    If you use subclassing a lot, that alone creates huge coupling. Representing that coupling in the filesystem too is another layer, which will make it very hard to later on modify your code. Namespacing and packaging based on the responsibilities of the classes/interfaces has proven to be the best way for me.

    This is a good piece of writing about how to think of responsibilities: http://blog.8thlight.com/uncle-bob/2014/05/08/SingleReponsibilityPrinciple.html