Build your own PHP Framework-abstract Controller base class-php Tutorial

Source: Internet
Author: User
Build your own PHP Framework-abstract the Controller's base class. in the previous blog, we moved simple route parsing and execution from the entry file publicindex. php to the framework. The entry file becomes refreshing ~~ However, let's take a look at our controller and we will see the following code: publicfunctionactionView () {$ body to build its own PHP Framework-abstract Controller base class

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

  */class Controller{}

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

Let's take a look

  */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.

 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.

  */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:

  */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:

            title                
 id;?>
action;?>

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.