WhiteProfileSpecialist
WhiteProfileSpecialist

Reputation: 119

PHP creating objects inside a base controller on demand

So i'm working on a framework (Yes i know it's overdone) and i was brainstorming what would be the best possible approach to achieve dynamic object creation inside a base controller. So i came up with the following solution:

Base controller

abstract class Controller extends Container
{
    public function __get($obj)
    {
         $this->$obj = $this->get($obj)
         return $this->obj;
    }
{

App controller

class Welcome extends Controller
{
    public function actionIndex()
    {
         $this->view->render('welcome');
    }
}

So now let me explain whats happening. The base controller extends a container which is a dependency injection class. It holds closures for creating objects. So when we try to access undefined property in welcome controller it calls the magic __get method. Then the base controller gets the binding from the DI container and defines it as a property so we can use it.

So everything works exactly as i wanted, but i know that magic methods are slow. I was wondering how would it impact performance when there is dozens of __get calls. Is there a better way of achieving the same thing without defining all classes manually in the base controller?

Upvotes: 0

Views: 439

Answers (1)

tereško
tereško

Reputation: 58444

First of all, that is not a DI Container. What you have there is a Service Locator, which you have inherited. If you user Service Locator with some care, it is a quite good pattern, but people usually abuse it and it turns into an architectural anti-pattern.

When you write extends in your code, it means that when you write class B extends A, you are stating that B is just a special case of A. Controllers are not service locators.

Next .. emm. You seem to be missing the point of controllers withing MVC and MVC-inspired architectures.

A controller can send commands to the model to update the model's state (e.g., editing a document). It can also send commands to its associated view to change the view's presentation of the model (e.g., by scrolling through a document).

source: wikipedia

Basically, what you are trying to attemt would both violate the basic principles of the pattern and also ignore Single Responsibility Principle. You would be turning a controller in some variation on Factory.

What this boils down to is: why is your controller producing instance and returning them?

Upvotes: 2

Related Questions