GGio
GGio

Reputation: 7653

PHP Custom MVC Framework using FrontController

I'm little bit confused. I want to build my own framework just to learn how everything works not that I will use it for big projects.

I have a FrontController class and this class has the route functionality inside.

  1. Functions to set/get Parameters for Controller
  2. Functions to set/get Actions (methods) from Controller
  3. Functions to parse the requested URI and return proper controller if exists if not returns default controller which is IndexController.
  4. Run() method that does the following:

    public function run() {
        $method    = new \ReflectionMethod($this->controller, $this->action);
        $numParams = $method->getNumberOfParameters();
    
        //fill missing parameters with null values
        if (count($this->params) != $numParams) {
           $tempArray = array_fill(0, $numParams, null);
           $this->setParams($this->params + $tempArray);
        }
    
        $controller   = new $this->controller;
    
        $userInstance = User::getInstance();
    
        //just creates a model based on the controller name by default its
        //Index.php (model)
        $model        = DB::createModel($this->getControllerName());
    
        //run _before before any function
        $controller->_before($model, $userInstance);
    
        call_user_func_array(array($controller, $this->action), $this->params);
        return;
    }
    

    now I've seen tutorials and they use BaseController and each Controller then extends from this basecontroller. My controllers do not extend from FrontController.

My question is Do i need a separate class for Routing? DO i need to split FrontController into

  1. BaseController
  2. Route.php
  3. Model.php

Since run() function actually passes the model and user object to the controller.

Upvotes: 1

Views: 1074

Answers (1)

Bart
Bart

Reputation: 17361

One basic principle to keep in mind is the Single Responsibility Principle. A well designed class has exactly one responsibility.

So yes. You will need to separate the routing and all other responsibilities.

Also note that the model must be considered a layer and not a class or object. The model layer is a collection of classes (data access, services). In fact, your User class should be considered part of that layer.

Here's an article which can help you understand the MVC pattern a bit better.

Upvotes: 2

Related Questions