Home > Article > Backend Development > Build your own PHP framework--the base class of abstract Controller_PHP tutorial
<?php namespace sf\base; /** * Controller is the base class for classes containing controller logic. * @author Harry Sun <sunguangjun@126.com> */ class Controller { }
<?php namespace 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'; } }
<?php namespace 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']); } }
<?php namespace 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; }
<?php namespace 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)]); } }
<html> <head> <title>title</title> <head> <body> <?php echo $this->id;?><br/> <?php echo $this->action;?><br/> <?php echo $body;?> </body> </html>
/** * Convert a array to json string * @param string $data */ public function toJson($data) { if (is_string($data)) { return $data; } return json_encode($data); }