Rooxie Rooxie - 6 months ago 15
PHP Question

Generating a corresponding name for models in PHP MVC

For purposes of learning MVC (I'm totally new to this) I am writing a mini-framework of my own. Perhaps my question will be pretty stupid and, for some, obvious, but I really couldn't google it, mainly because I don't know how to google it. Also, sorry for the long, redundant post.

My

Router
class works this way
www.example.com/controller/controller_method
.

All my controllers and models have the same prefix in their names. For example I have the
UsersController
class and the corresponding
UsersModel
class.

Controllers and Models are the instances of the corresponding abstract classes. For instance here's the controller class:

abstract class Controller
{
protected $model;

public function __construct(Model $model)
{
$this->model = $model;
}
}


And now the question. I'm instantiating the corresponding model inside the controller constructor this way:

class UsersController extends Controller
{
public function __construct()
{
parent::__construct(new UsersModel());
}
}


But would it be right/acceptable/adequate to do it this way:

class UsersController extends Controller
{
public function __construct()
{
$model = str_replace("Controller", "Model", __CLASS__);
parent::__construct(new $model());
}
}


Or, may be even better, like this:

abstract class Controller
{
protected $model;

public function __construct($classname)
{
$model = str_replace("Controller", "Model", $classname);
$this->model = new $model();
}
}


So the constructor of the child would be:

public function __construct()
{
parent::__construct(__CLASS__);
}


This seems more automated but, perhaps, it may be poor/slow/stupid design decision? The main reason I'm worried is that
__CLASS__
constant is magic, and I read somewhere that magic methods/constants can be 2-24x slower.

Answer

No need to fuss about in the child class:

abstract class Controller
{
    protected $model;

    public function __construct()
    {
        $modelName = str_replace("Controller", "Model", get_class($this));
        $this->model = new $modelName;
    }
}

Courtesy of the second answer to this question: Getting the name of a child class in the parent class (static context)

Note: requires php 5.2.9