Build your own PHP framework-Abstract The Controller base class, framework controller

Source: Internet
Author: User
Tags tojson

Build your own PHP framework-Abstract The Controller base class, framework controller

In the previous blog, we resolved and executed simple routes and moved them from the public/index. php file to the framework. The entry file becomes refreshing ~~

However, go to our controller and check the following code:

    public function actionView()    {        $body = 'Test body information';        require '../views/site/view.php';    }

Does it mean that every time we write an action to render a page, we need to find the view in the corresponding path and then request it in. This is definitely not the case. Therefore, we need to abstract a base class of Controller to implement a method for rendering pages, so that other controllers can inherit them and use the corresponding method.

Needless to say, the controller's base class must be written into the framework. In addition, two parameters must be written, one in the base, the other in the web, and the Controller in the web inherits from the base.

Let's look at

<?phpnamespace sf\base;/** * Controller is the base class for classes containing controller logic. * @author Harry Sun <sunguangjun@126.com> */class Controller{}

There is only one empty class, waiting to add content.

Let's take a look

<?phpnamespace sf\web;/** * Controller is the base class for classes containing controller logic. * @author Harry Sun <sunguangjun@126.com> */class Controller extends \sf\base\Controller{    /**     * Renders a view     * @param string $view the view name.     * @param array $params the parameters (name-value pairs) that should be made available in the view.     */    public function render($view, $params = [])    {        extract($params);        return require '../views/' . $view . '.php';    }}

As you can see, we first import the variables from the array to the current symbol table, and then introduce the corresponding view page.

Then, in SiteController, we only need to write it like this.

<?phpnamespace app\controllers;use sf\web\Controller;class SiteController extends Controller{    public function actionTest()    {        echo 'success!';    }    public function actionView()    {        $this->render('site/view', ['body' => 'Test body information']);    }}

Then, access http: // localhost/simple-framework/public/index. php? R = site/view, you can see the same page as before.

Let's improve the Controller in the base.

<?phpnamespace sf\base;/** * Controller is the base class for classes containing controller logic. * @author Harry Sun <sunguangjun@126.com> */class Controller{    /**     * @var string the ID of this controller.     */    public $id;    /**     * @var Action the action that is currently being executed.     */    public $action;}

Two attributes are added to record the current controller and action respectively.

Then, assign a value to the router after parsing it. The code is as follows:

<?phpnamespace sf\web;/** * Application is the base class for all application classes. * @author Harry Sun <sunguangjun@126.com> */class Application extends \sf\base\Application{    /**     * Handles the specified request.     * @return Response the resulting response     */    public function handleRequest()    {        $router = $_GET['r'];        list($controllerName, $actionName) = explode('/', $router);        $ucController = ucfirst($controllerName);        $controllerNameAll = $this->controllerNamespace . '\\' . $ucController . 'Controller';        $controller = new $controllerNameAll();        $controller->id = $controllerName;        $controller->action = $actionName;        return call_user_func([$controller, 'action'. ucfirst($actionName)]);    }}

Then we can get the corresponding controller name and action name in the controller and view, and modify view. php as follows:

Then we can see the following page.

Some people think that the frontend and backend are separated. We don't need to use PHP to render a page. We only need to return a josn string, which is simpler, add a toJson Method to the web Controller.

    /**     * Convert a array to json string     * @param string $data     */    public function toJson($data)    {        if (is_string($data)) {            return $data;        }        return json_encode($data);    }

Modify actionTest in SiteController as follows:

    public function actionTest()    {        $data = ['first' => 'awesome-php-zh_CN', 'second' => 'simple-framework'];        echo $this->toJson($data);    }

Access http: // localhost/simple-framework/public/index. php? R = site/view, you can see the corresponding json string.

 

Now, we will be here today. The project content and Blog content will also be put on Github. You are welcome to give suggestions.

Code: https://github.com/CraryPrimitiveMan/simple-framework/tree/0.3

Blog project: https://github.com/CraryPrimitiveMan/create-your-own-php-framework

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.