First of all ... Do not put the startup script in the routing mechanism. You mix duties. You will be better off creating a separate class for this based on spl_autoload_register .
Neeext .. do no the complexity of operations on the constructor. This forces you to code a few unverifiable. Perhaps you should have something like:
// you might want to replace $_GET with $_SERVER['QUERY_STRING'] later $router = new Router( $_GET['url'] ); // where 'default' is the name of fallback controller $controller_class = $router->get_controller( 'default' ); $method_name = $router->get_action( 'index' ); $model_factory = new ModelFactory( new PDO( ... ) ); $controller = new {$controller_class}( $model_factory ); $controller->{$method_name}();
Also, you should look into php namespaces . It makes no sense to end the class ...Controller to know where the class will be.
Good ... back to the Model.
There is a fairly common misconception regarding models in the web development community (I blame RoR for this mess). A model in MVC is not a class , but an application layer that contains many instances. Most instances belong to one of two types of classes. With the following responsibilities:
Domain Logic :
Transactions with all calculations, calculations and all the detailed data about the domain. The objects in this group do not know where and how the data is stored. They only manage information.
Data access
Usually made from objects that match the DataMapper pattern (do not confuse with ORM with the same name .. nothing to do). Responsible for storing data from domain objects and their receipt. Maybe in the database .. maybe not. Your SQL queries will be here.
In a semi-real-world situation (), it might look something like this (referring to the abowe code):
class SomeController { // ... snip ... protected $model_factory = null; // ... snip ... public function __construct( ModelFactory $factory ) { $this->model_factory = $factory; } // ... snip ... public function action_foobar() { $user = $this->model_factory->build_object( 'User' ); $mapper = $this->model_factory->build_mapper( 'User' ); $user->set_id(42); $mapper->fetch($user); if ( $user->hasWarning() ) { $user->set_status( 'locked' ); } $mapper->store( $user ); } // ... snip ... }
As you can see, there is no indication of how the data was saved. It doesn't even matter if the user account was new or already exists.
Some materials you may find useful
Video
Books:
source share