Note that there are some explanatory texts on larger screens.

plurals
  1. POIn a PHP project, what patterns exist to store, access and organize helper objects?
    text
    copied!<p>How do you organize and manage your helper objects like the database engine, user notification, error handling and so on in a PHP based, object oriented project?</p> <p>Say I have a large PHP CMS. The CMS is organized in various classes. A few examples:</p> <ul> <li>the database object</li> <li>user management</li> <li>an API to create/modify/delete items</li> <li>a messaging object to display messages to the end user</li> <li>a context handler that takes you to the right page</li> <li>a navigation bar class that shows buttons</li> <li>a logging object</li> <li>possibly, custom error handling</li> </ul> <p>etc.</p> <p>I am dealing with the eternal question, how to best make these objects accessible to each part of the system that needs it.</p> <p>my first apporach, many years ago was to have a $application global that contained initialized instances of these classes.</p> <pre><code>global $application; $application-&gt;messageHandler-&gt;addMessage("Item successfully inserted"); </code></pre> <p>I then changed over to the Singleton pattern and a factory function:</p> <pre><code>$mh =&amp;factory("messageHandler"); $mh-&gt;addMessage("Item successfully inserted"); </code></pre> <p>but I'm not happy with that either. Unit tests and encapsulation become more and more important to me, and in my understanding the logic behind globals/singletons destroys the basic idea of OOP.</p> <p>Then there is of course the possibility of giving each object a number of pointers to the helper objects it needs, probably the very cleanest, resource-saving and testing-friendly way but I have doubts about the maintainability of this in the long run. </p> <p>Most PHP frameworks I have looked into use either the singleton pattern, or functions that access the initialized objects. Both fine approaches, but as I said I'm happy with neither. </p> <p>I would like to broaden my horizon on what common patterns exist here. I am looking for examples, additional ideas and pointers towards resources that discuss this from a <strong>long-term</strong>, <strong>real-world</strong> perspective. </p> <p>Also, I'm interested to hear about specialized, niche or <strong>plain weird</strong> approaches to the issue.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload