I am currently rewriting a legacy PHP4 application to a MVC-style object-oriented one.
As the most complex part is the models, I came up with the following controller-view scheme. I wanted to use only variables in my views, using only <? if ($foo === 'bar'): ?>
-like blocks if necessary. The controllers instead generate the variables for the views from the data generated by my models.
Is the following a good approach to MVC code separation?
The controller code looks like this:
interface InterfaceController {
public function setup();
public function compile();
}
abstract class AbstractPageController implements InterfaceController
{
public static $variables = array();
public static $template = '';
public function compile() {
static::$variables['header'] = Controller::run('partials/header');
static::$variables['footer'] = Controller::run('partials/footer');
return (new View(static::$template, static::$variables))->render();
}
}
class ExampleController extends AbstractPageController
{
public function setup() {
$variables['foo'] = 'bar';
static::$template = 'examplepage';
static::$variables = $variables;
return $this;
}
}
An example route would look like that:
/* ... */
Route::get('/example/supercoolfeature', function() {
Controller::run('example/features/supercool');
});
/* ... */
So, the router calls the following Controller class:
class Controller
{
/**
* Executes a controller:
* If called as "Controller::run('foo/bar')", the function will call the
* class "App\Controllers\Foo\BarController" and execute the setup() and run()
* methods.
*/
public static function run($name) {
$parts = array();
foreach (explode('/', $name) as $part) {
// uppercase each controller path part so you can
// go lowercase in the actual code
$parts[] = ucfirst($part);
}
// attach the parts together and append "Controller" at the end
$name = '\\App\\Controllers\\' . implode('\\', $parts) . 'Controller';
// run the controller, let it prepare a view and return the rendered code
return (new $name())->setup()->compile();
}
}
And finally, the respective view for the controller:
<?php echo $header; ?>
<div class="hi">
<h1>Hi there, <?php echo $foo; ?>!</h1>
</div>
<?php echo $footer; ?>