How to acess multiple classes through one parent class in PHP - php

Lets say I have a class called PageBuilder which I instantiate, send parameters to and call functions from through my index file (which acts as a front controller). There are three sub classes associated with the PageBuilder class: Head, Body and Foot, that are accessed by PageBuilder which basically abstracts them for index.
So in theory you could instantiate PageBuilder and have full access to the other classes as if they were part of PageBuilder.
How can I implement a design like this in PHP5 using any combination of classes, abstract classes and interfaces?
I don't think the above is possible with PHP5, not necessarily because PHP has its limitations but maybe because I am going about the design of my application the wrong way.
Common examples of OOP in PHP don't suffice to help me understand how to structure a more complex design.
Thanks.

Some of the other answers are on the right track. The problem you're running into is that your PageBuilder class is doing too much. Just the name sounds wrong for what you're trying to do with it. A PageBuilder sounds like something that would assemble a bunch of parts together into a Page. Let's call these parts Section. Then, what you want to do is use composition, as several of the answers have hinted at.
Inheritance is often described as an is-a relationship, as in if your Section classes extend the PageBuilder class, then a Section is a PageBuilder. What you want though is a has-a relation ship, as in your PageBuilder class has a (or many) Section(s). Any time you need a has-a relationship, you should be looking toward composition rather than inheritance.
So here might be your class hierarchy:
abstract class PageBuilder
{
//#var Section
public $header;
//#var Section
public $body;
//#var Section
public $footer;
public function render()
{
echo $this->header.$this->body.$this->footer;
}
}
class Section
{
protected $content;
}
class LoginPage
extends PageBuilder
{
public function __construct()
{
$this->header=new Section(...);
$this->footer=new Section(...);
$this->body=new Section(...);
}
}
At this point, you're really kind of re-inventing the wheel by making a crappy MVC system. If this is for a project (rather than for learning), you should consider using one of the MVC frameworks for PHP. (I recommend Kohana, but there are several questions regarding the best PHP versions on Stack Overflow.) If you're thinking of these kinds of things, MVC probably won't be a great leap for you.

From what I understand here you could use the composite pattern
http://en.wikipedia.org/wiki/Composite_pattern
Your controller index has only access to an object that implements an interface IPageBuilder (or a name similar), with some standards function like "generatePage". This object would in reality be some kind of container that contain other object of type IPageBuilder. Those leafs object would be able to build some subsection of the page, like Head, Body and Foot. Each of those leaf object would be of a different class, but they will implement the IPageBuilder interface. When your index object call "generatePage", the container will call in order the "generatePage" method of each of its leaf objects, that will in turn take care of rendering the HTML.
Using this approach, if your Body class become too big, you can always turn it into a container that implements the IPageBuilder interface, for example a blog post Body could consist of an Article object and a CommentList object. The body object would then only propagate the "generatePage" method to its children object.
To create your IPageBuilder object, you can use a factory patterns
http://en.wikipedia.org/wiki/Factory_method_pattern
In all honesty, I have tried those kind of approach in the past to generate my HTML and found them to be kind of overkill. My suggestion would be to use a templating engine instead, like Smarty. Your designer will love you (or hate you less) if do that ^^.
http://www.smarty.net/
If you want to know how to use interfaces in PHP, not that it's very hard...
http://ca.php.net/manual/en/language.oop5.interfaces.php

So if I understand correctly you want Head, Body, and Foot to automatically construct as children of PageBuilder?
There are a couple of ways you could maybe do this.
1) Create variables inside of PageBuilder to hold the classes and use a __call method
class PageBuilder{
private _head;
private _body;
private _foot;
function __construct(){
$this->_head = new Head();
$this->_foot = new Foot();
$this->_body = new Body();
}
function __call($name, $args){
if(method_exists($this->_head, $name)) call_user_func_array(array($this->head, $name), $args);
// Repeat for other classes.
}
}
The problem here obviously being if two classes share the same method then the first one to come up wins. You could probably modify it to pick a class based on the function name pretty easily.
2) Chain everything down.
Abstract class Page{
}
class Head extends Page{
}
class Body extends Head{
}
class Foot extends Body{
}
class PageBuilder extends Foot{
}
Either way its somewhat hacked, you just kind of have to make it work.

PHP only allows you to extend one parent class (which can in turn extend another parent class, etc.). There are no interfaces, meaning you can't inherit functions or properties from multiple interfaces as you could in C++.
As such, you will probably need to do something more like this:
class PageBuilder {
protected Head, Body, Foot;
public function __construct($request) {
$view = $this->getView($request);
$this->Head = new PageSection('head.tpl');
$this->Body = new PageSection($view);
$this->Foot = new PageSection('foot.tpl');
}
private function getView($request) {
// #todo return the template filename/path based upon the request URL
}
}
class PageSection {
private $template;
public function __construct($template) {
$this->template = $template;
}
public function render() {
// #todo process and output the $this->template file
}
}

Related

Organizing classes and properties in PHP - the right way?

Please help me. I need a better understanding PHP OOP principles.
If I have a class property which is immutable for all of the class instances it should be defined as static?
If so, is there a way to be sure that static properties are defined in all classes of that type? As I read in PHP manual, static properties cannot be controller neither by the interface nor by abstract classes? Or am I wrong?
Simple example.
<?php
// Parent class
abstract class Employee
{
abstract public function getAlias();
}
// Child classes
class Manager extends Employee
{
public function getAlias()
{
return 'manager';
}
}
class Security extends Employee
{
public function getAlias()
{
return 'security';
}
}
Tell me, where an alias property should be placed?
I have to be sure that any Employee descendants that will be created in future will have that property defined. Is it OK to keep that kind of properties in dynamic methods? Or they should be placed in constants, static methods or static properties?
Actually the current version is quite ok (if considered with no context) because it makes for a cleaner code, since it closer matches principle of least astonishment. Technically, you could rewrite it as this (but that would actually make it worse code):
abstract class Employee {
public function getAlias() {
return $this->alias;
}
}
class Manager extends Employee {
protected $alias = 'mngr';
}
$user = new Manager;
echo $user->getAlias();
Live code: https://3v4l.org/sjVOT
The more important aspect is the purpose of this code. You mentioned, that you would want to use something like this for dealing with single-table inheritance, but here is the important part:
Your domain entities should not be aware of how your persistence layer works.
And pulling structural information from the domain layer for use in some query-builder is a terrible idea. I would recommend for you to instead looks at data mapper pattern (you probably should actually read the PoEAA book).
Your domain entities should not know any details about how (or even "if") they is being saved or restored.

optional dependencies within a class

I'm looking for some direction regarding the following, I'm new to OOP and getting there but think either my lack of understanding is causing me to get stuck in a rabbit hole or I'm just over thinking things too much and being anal.
basically i have a main class called "CurlRequest" which sole purpose is to perform curl requests, providing a url and params it returns me some html. This class works and functions as intended and I'm happy with that.
I use this class for a few projects but for one I then wanted to track the performance of my requests made. attempted, failed, passed etc, so i created a static class for this which manages all my counters. I place counter references like the following at different areas in my CurlRequest class.
PerformanceTracker::Increment('CurlRequest.Attempted');
PerformanceTracker::Increment('CurlRequest.Passed');
PerformanceTracker::Increment('CurlRequest.Failed');
I have around 10 or so of these with my class tracking all kinds of things during the curl request and i also use my PerformanceTracker class in other classes i made.
However like mentioned i only wanted to do this for one of my projects, so find my self in the situation of having my original CurlRequest class and an altered one with performance counters in it.
My question is, is their a way i can use the same class for any project and choose to use the PerformanceTracker class or not. The obvious way i thought of was to pass an $option argument into the class and then have if statements around all the counters, but can't help think its messy.
if ($this->options['perfCounter'] == true ) {
PerformanceTracker::Increment($this->owner . '.CurlRequest.Failed');
}
this also adds a lot of extra code to the class.
I suggest placing the if statement in a separate method
private function handlePerformanceTracker($q)
{
if ($this->options['perfCounter'] == true ) {
PerformanceTracker::Increment($q);
}
}
And call this method instead of your calls to
PerformanceTracker::Increment(...);
Also if you find that you want to track performance differently between your projects it might be useful to change your constructor to accept a callable argument, this way you externalize the actual implementation from the CurlRequest class itself.
public function __construct(..., callable performanceHandler)
Then when you instantiate your class:
$curlRequest = new CurlRequest(..., function($outcome) {
//your implementation
});
You can use inheritance and create a subclass that performs the logging before delegating to the parents methods:
class PerformanceTracker
{
static function Increment($s)
{
echo $s;
}
}
class CurlRequest
{
function get($url){
//preform curl request, save html to variable etc
//dummy vars used here so working example code
$html = 'html here';
$curlError = false;
if($curlError){
$this->error($curlError);
}
return $this->success($html);
}
protected function success($html)
{
return $html;
}
protected function error($curlError)
{
throw new Exception($curlError);
}
}
class LoggingCurlRequest extends CurlRequest
{
function get($url)
{
PerformanceTracker::Increment('CurlRequest.Attempted');
return parent::get($url);
}
function success($html)
{
PerformanceTracker::Increment('CurlRequest.Passed');
return parent::success($html);
}
function error($curlError)
{
PerformanceTracker::Increment('CurlRequest.Failed');
parent::error($curlError);
}
}
$lcr = new LoggingCurlRequest();
$lcr->get('unused in example');
As i have used dummy classes with minimal code to demo the technique the benefit might not be obvious, but in you real code, the methods in the CurlRequest class will be more complex, but the methods in the logging class will remain as two liners, with the log function and the call to the parent method.
Using this technique you can modify the parent class without effecting the derived classes (provided the method signatures dont change), can create other derived classes (how about a CachingCurlRequest) etc.
For the full benefits of OOP you should look into dependency injection and interfaces
From an OOP perspective you could use the 'Null' object pattern. This just means that the dependency used by the CurlRequest class is abstract (possibly an interface?). You would then have Two concrete implementations of PerformanceTracker: the one you have today and one that does nothing (it does not have any behavior). In this way for the one project when you instantiate the CurlRequest class it would use the concrete implementation that has behavior and for all the other projects it would use the concrete implementation with no behavior. All of the code in CurlRequest would look the same but it would have different behavior depending on which concrete implementation it was using

Intercepting method progression based on condition checked by parent class

This is a very basic architectural question and it is thus very hypothetical.
Imagine this simple setup:
I have a class representing a web object, with only one method that renders the object. However, this class extends a parent class which requires certain conditions to be met, so that the method is actually executed (so that the object is being rendered).
Example
class webObject__adminBase {
protected function shouldRender(){
return access::isAdmin();
}
}
class webObject__adminPanel extends webObject__adminBase {
public function invoke(){
if(!parent::shouldRender())
return;
// if still here, render the object
}
}
$panel = new webObject__adminPanel();
$panel->invoke();
The code above serves both: an example plus a practical explanatory approach to the problem.
The issue is: i would like to get around this problem without actually having to call a method in my parent class in the child's rendering method.
I would like to achieve a class design that assures that all i need to do is to extend the parent class webObject__adminBase. Any calls to any methods in my child class should be checked against certain conditions (as in this example systemAccess::isAdmin()) and only render if these conditions are met.
I hope my description is clear.
Since someone actually requested to close this question as "too broad", i decided to rephrase my actual question with a more direct reference to the question title:
Is there a way to intercept the progression (or even execution) of a child's method based on a condition checked for by its parent class (without calling a method on that parent class) ?
Here is one method of doing it, albeit quite simple. I'm sure there are better methods but this one tries to keep to your original methodology.
https://ideone.com/D5hA3H
Render Class
abstract class Render
{
abstract public function main();
public function __construct()
{
}
final public function render()
{
if (!$this->canRender()) return '';
return $this->main();
}
final public function canRender()
{
// Logic here
return true;
}
}
Admin Panel Class
class AdminPanel extends Render
{
public function main()
{
return "Admin Panel";
}
}
Execution
$panel = new AdminPanel();
echo $panel->render();
PeeHaa is right about the naming conventions, it is in the best interest to try and follow a popular coding style which allows you yourself to read code easier and vice versa. You might want to take a look at the PHP-FIG PSR one and two standards which helps in creating consistent code.
PHP The Right Way is also a great website that will help you out the most, it provides information about dependency injection and coding practices amongst other things.

php - class extending alternative

I have a main class that I add around a dozen child classes to similar to Example #2.
I'm wondering if there is a better way to accomplish this. I know I could do "extends" on classes (Example #1) however in order to be able to have one variable with access to all extended class functions, I'd have to "daisy chain" the extensions and then create a new class reference on the very last extension - this option is not what I'm looking for.
Example #1:
class main {
function _construct(){}
function main_function1(){}
function main_function2(){}
}
class child1 extends main{
function _construct(){}
function child_function1(){}
function child_function2(){}
}
class child2 extends child1 {
function _construct(){}
function child_function3(){}
function child_function4(){}
}
$main = new child2();
$main->child_function1();
$main->child_function2();
$main->child_function3();
$main->child_function4();
Here is what I'm currently doing.
Example #2:
<?php
class main {
function _construct(){}
function main_function1(){}
function main_function2(){}
}
class child1 {
function _construct($main){$this->main = $main;}
function child_function1(){}
function child_function2(){}
}
class child2 {
function _construct($main){$this->main = $main;}
function child_function3(){}
function child_function4(){}
}
$main = new main();
$main->child1 = new child1($main);
$main->child2 = new child2($main);
$main->child1->child_function1();
$main->child1->child_function2();
$main->child2->child_function3();
$main->child2->child_function4();
?>
Is Example #2 the best way to achieve what I'm looking for?
By doing
class child {
function __construct($main){$this->main = $main;}
}
in Example 2 you would pass the $main instance as a property for child in the constructor. In my opinion this would make sense, if $main is a container that provides information for child - which is useful if you would like to avoid having a constructor with many many arguments. According to your naming, it doesn't look like main is a container. Be aware, that you are creating a dependency between child and main then because if you want to instantiate child, you always need an instance of main in advance! What you are also doing in Example 2 is creating circular references:
$main = new main();
$main->child1 = new child1($main);
$main->child2 = new child2($main);
You would be able to call $main->child1->main then which means a high coupling between main and child. So I'd rather not say "go for Example 2".
In your case it rather sounds like child actually is a special case of main, like the relationship between fruit (main) and apple (child). That makes using extends much more reasonable. You seem to be unsure, because you have many child classes extending main. To me this sound just normal, if all the child classes have a similar purpose and share some basic functionalty which is provided by main. But I'm not quite sure what your goal actually is.
Extending classes can break encapsulation, so depending on your classes it might be best to keep your objects separated as in example #2. You could have a loading function to make setting up the main class easier:
class main {
function load($class){
$this->$class = new $class();
}
}
$main = new main();
$main->load('child1');
$main->child1->child_function1();
In php, You have two options. Either (in 2020) inject your Helper Class in another class as suggested in the first answer or in PHP you can use traits.
Traits are similar to classes but their constructors cannot be public.
It's difficult to use Dependency injection on traits but traits can extend existing classes with methods and they can access the parent methods of their respective classes.
With traits anyway you cannot override the parent methods, you can only add the methods to the stack.
Another downside of traits is that, when you use the parent methods of the containing class, type hinting is not well supported in some IDEs. So in order to get type hinting working you'll need some workarounds.

How would I build a PHP class?

I have a parent class, let's say class main { ... }, and an extension of it, let's call it class extension extends main { ... }.
My question is, how would I build another class, called class messages { ... }, which I can use inside the main class and the extended class of main, extension ? Besides the way I know, calling the class messages like this :
$messages = new messages;
$messages->someMethod();
Is there another way without having to do new ... to make the main and extension class inherit the methods inside the messages class ?
AFAIK, PHP does not support multiple inheritance, as others OOP languages do.
So, no, there is NOT another way.
And yes, you should create a property and instantiate the object inside the main class...
class main {
public $messages; // may be "protected" or "private" instead
public __construct()
{
$this->messages = new messages();
}
public do_something()
{
$this->messages->do_something_else();
}
}
However, there are alternatives to simulate a fake multiple inheritance.
An alternative would be: https://stackoverflow.com/a/356431/370290 - But I don't recommend this (even the own author doesn't).
Another alternative: https://stackoverflow.com/a/358562/370290 - IMHO, as weird as the previous one. :-)
And as of PHP 5.4.0 you can also use traits to achieve a "multiple inheritance" effect: http://php.net/manual/en/language.oop5.traits.php - This is very new at the moment.
You can't extend multiple classes and to exten the main class .. only a good thing if you extend from an abstract class.
But what you could do is add it in the construct of your main class like this:
//member variable for class main
public $_message = null;
public function __construct()
{
$this->_message = new Message();
}
Then whenever you need the message class just call $this->_message + the method you need (eg: $this->_message->addMessage())
don't forget to add this in you subclass:
public function __construct()
{
parent::__construct();
}
The problem you seem to have is that you can't do multiple inheritance (class YourClass extends main, messages).
The common feeling is that if you need multiple enheritance, you're doing something wrong in your design.
Every class is responsible for a single thing. A "extension" in this case "IS A" "main", but it is not a "messages", so it should not be a child of that. IF you need messaging capability, there is no 'shame' at all in just calling it like you suggest: you get yourself a nice object that knows how to message, and play with that. There is no real need to do it differently.
If you're looking for alternatives (which you really don't need as far as I can see!) you could make it a class with a bunch of static methods, and just call it like messages::someMethod(), but I think that would be considered an anti-pattern in this case.
Just go with it: messages are created by an object of type message. So you make one, and call the function. In the end, if you ever need big changes (database connection, logging, etc etc) for you messaging, you can do this all in your nice and cosy messaging class. Everyone happy :)
You should create a class inside a class. Just like in this question.
Then, you can use $this->someclass->function.
Note: construct needs to be $this->someclass = new Whatever() too.

Categories