Php MVC控制器的一个示例

Php MVC控制器的一个示例,php,model-view-controller,Php,Model View Controller,我已经读了很多关于如何以及为什么在应用程序中使用MVC方法的书。我看到并理解了模型的例子,我看到并理解了视图的例子。。。。但我对控制器还是有点模糊。我真的很想看到一个足够全面的控制器示例。(如果可能,使用PHP,但任何语言都会有所帮助) 多谢各位 PS:如果我能看到index.php页面的一个示例,它决定使用哪个控制器以及如何使用,那也太好了 编辑:我知道控制器的工作是什么,但我真的不知道如何在OOP中实现这一点。想象一下UI中的三个屏幕,一个用户输入一些搜索条件的屏幕,一个显示匹配记录摘要列表

我已经读了很多关于如何以及为什么在应用程序中使用MVC方法的书。我看到并理解了模型的例子,我看到并理解了视图的例子。。。。但我对控制器还是有点模糊。我真的很想看到一个足够全面的控制器示例。(如果可能,使用PHP,但任何语言都会有所帮助)

多谢各位

PS:如果我能看到index.php页面的一个示例,它决定使用哪个控制器以及如何使用,那也太好了


编辑:我知道控制器的工作是什么,但我真的不知道如何在OOP中实现这一点。

想象一下UI中的三个屏幕,一个用户输入一些搜索条件的屏幕,一个显示匹配记录摘要列表的屏幕,以及一个一旦选择一条记录就显示以供编辑的屏幕。将有一些逻辑与最初的搜索有关

if search criteria are matched by no records
    redisplay criteria screen, with message saying "none found"
else if search criteria are matched by exactly one record
    display edit screen with chosen record
else (we have lots of records)
    display list screen with matching records

这种逻辑应该走向何方?当然不在视图或模型中?因此,这是控制器的工作。控制器还将负责获取标准并调用模型方法进行搜索。

请求示例

index.php中放入类似的内容:

<?php

// Holds data like $baseUrl etc.
include 'config.php';

$requestUrl = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$requestString = substr($requestUrl, strlen($baseUrl));

$urlParams = explode('/', $requestString);

// TODO: Consider security (see comments)
$controllerName = ucfirst(array_shift($urlParams)).'Controller';
$actionName = strtolower(array_shift($urlParams)).'Action';

// Here you should probably gather the rest as params

// Call the action
$controller = new $controllerName;
$controller->$actionName();
请检查以下内容:

    <?php
    global $conn;

    require_once("../config/database.php");

    require_once("../config/model.php");

    $conn= new Db;

    $event = isset($_GET['event']) ? $_GET['event'] : '';

    if ($event == 'save') {
        if($conn->insert("employee", $_POST)){
            $data = array(
                'success' => true,
                'message' => 'Saving Successful!',
            );
        }

        echo json_encode($data);
    }

    if ($event == 'update') {
        if($conn->update("employee", $_POST, "id=" . $_POST['id'])){
            $data = array(
                'success' => true,
                'message' => 'Update Successful!',
            );
        }

        echo json_encode($data);
    }

    if ($event == 'delete') {
        if($conn->delete("employee", "id=" . $_POST['id'])){
            $data = array(
                'success' => true,
                'message' => 'Delete Successful!',
            );
        }

        echo json_encode($data);
    }

    if ($event == 'edit') {
        $data = $conn->get("select * from employee where id={$_POST['id']};")[0];
        echo json_encode($data);
    }
?>

  • 创建文件夹结构
  • Setup.htaccess和虚拟主机
  • 创建配置类以构建配置数组
  • 控制器
  • 使用受保护的非静态和getter创建路由器类
  • 使用config include&autoload和include路径(lib、controlelrs、models)创建init.php
  • 使用路由、默认值(路由、控制器、操作)创建配置文件
  • 在路由器中设置值-默认值
  • 设置uri路径,分解uri并设置路由、控制器、操作、参数、进程参数
  • 通过传递uri创建应用程序类以运行应用程序-(受保护的路由器obj,运行func)
  • 创建控制器父类以继承所有其他控制器(受保护的数据、模型、参数-非静态) 在构造函数中设置数据、参数
  • 创建控制器并使用上面的父类进行扩展,并添加默认方法
  • 在run函数中调用控制器类和方法。方法必须具有前缀
  • 如果存在,则调用该方法
  • 意见
  • 创建父视图类以生成视图。(数据,路径)使用默认路径,将控制器、渲染函数设置为 返回完整的临时路径(非静态)
  • 使用ob_start()创建渲染函数,ob_get_clean返回并将内容发送到浏览器
  • 更改应用程序类以解析要查看的数据类。若返回路径,则也传递给视图类
  • 布局。布局取决于路由器。重新解析布局html以查看和呈现

  • +1我最近一直在阅读和搜索MVC,这(对我来说)是我认为我见过的最清晰的控制器示例。logoutAction不属于LogoutController吗?或者只是将其想象为AuthController.:)重要的是要注意,这个例子不考虑安全性。该示例未实现使脚本容易受到攻击的任何编码和特殊字符。为什么?因为脚本将url中的任何内容(
    $\u SERVER['REQUEST\u URI']
    )注入PHP脚本。“不过MVC控制器的例子很好,很清晰。谢谢你的评论,@kristoferbohmann。”。的确,URI(以及我们试图提取的结果控制器和操作名称)没有额外的验证。但我没有看到“注入”在这里进行,或者我遗漏了什么?当你想到控制器时,想想流量控制。简单地说,另一个开发人员应该能够查看您的控制器,并清楚地了解该操作的作用以及它是如何完成的,而无需详细说明。您应该可以看到我的集中式
    index.php
    。这取决于URL重写。那么,对于300分,我的scribble能否满足您对基于控制器(MVC)系统的定义@Anthony Rutledge我没有看到控制器,因为我在这里会认出它。您的模型有一个getView()方法,对我来说,这意味着该模型承担了MVC意义上控制器的某些功能。添加一些注释会有所帮助
        <?php
        global $conn;
    
        require_once("../config/database.php");
    
        require_once("../config/model.php");
    
        $conn= new Db;
    
        $event = isset($_GET['event']) ? $_GET['event'] : '';
    
        if ($event == 'save') {
            if($conn->insert("employee", $_POST)){
                $data = array(
                    'success' => true,
                    'message' => 'Saving Successful!',
                );
            }
    
            echo json_encode($data);
        }
    
        if ($event == 'update') {
            if($conn->update("employee", $_POST, "id=" . $_POST['id'])){
                $data = array(
                    'success' => true,
                    'message' => 'Update Successful!',
                );
            }
    
            echo json_encode($data);
        }
    
        if ($event == 'delete') {
            if($conn->delete("employee", "id=" . $_POST['id'])){
                $data = array(
                    'success' => true,
                    'message' => 'Delete Successful!',
                );
            }
    
            echo json_encode($data);
        }
    
        if ($event == 'edit') {
            $data = $conn->get("select * from employee where id={$_POST['id']};")[0];
            echo json_encode($data);
        }
    ?>
    
    <?php
    class Router {
    
        protected $uri;
    
        protected $controller;
    
        protected $action;
    
        protected $params;
    
        protected $route;
    
        protected $method_prefix;
    
        /**
         * 
         * @return mixed
         */
        function getUri() {
            return $this->uri;
        }
    
        /**
         * 
         * @return mixed
         */
        function getController() {
            return $this->controller;
        }
    
        /**
         * 
         * @return mixed
         */
        function getAction() {
            return $this->action;
        }
    
        /**
         * 
         * @return mixed
         */
        function getParams() {
            return $this->params;
        }
    
        function getRoute() {
            return $this->route;
        }
    
        function getMethodPrefix() {
            return $this->method_prefix;
        }
    
            public function __construct($uri) {
                $this->uri = urldecode(trim($uri, "/"));
                //defaults
                $routes = Config::get("routes");
                $this->route = Config::get("default_route");
                $this->controller = Config::get("default_controller");
                $this->action = Config::get("default_action");
                $this->method_prefix= isset($routes[$this->route]) ? $routes[$this->route] : '';
    
    
                //get uri params
                $uri_parts = explode("?", $this->uri);
                $path = $uri_parts[0];
                $path_parts = explode("/", $path);
    
                if(count($path_parts)){
                    //get route
                    if(in_array(strtolower(current($path_parts)), array_keys($routes))){
                        $this->route = strtolower(current($path_parts));
                        $this->method_prefix = isset($routes[$this->route]) ? $routes[$this->route] : '';
                        array_shift($path_parts);
                    }
    
                    //get controller
                    if(current($path_parts)){
                        $this->controller = strtolower(current($path_parts));
                        array_shift($path_parts);
                    }
    
                    //get action
                    if(current($path_parts)){
                        $this->action = strtolower(current($path_parts));
                        array_shift($path_parts);
                    }
    
                    //reset is for parameters
                    //$this->params = $path_parts;
                    //processing params from url to array
                    $aParams = array();
                    if(current($path_parts)){ 
                        for($i=0; $i<count($path_parts); $i++){
                            $aParams[$path_parts[$i]] = isset($path_parts[$i+1]) ? $path_parts[$i+1] : null;
                            $i++;
                        }
                    }
    
                    $this->params = (object)$aParams;
                }
    
        }
    }
    
    <?php
    
    class App {
        protected static $router;
    
        public static function getRouter() {
            return self::$router;
        }
    
        public static function run($uri) {
            self::$router = new Router($uri);
    
            //get controller class
            $controller_class = ucfirst(self::$router->getController()) . 'Controller';
            //get method
            $controller_method = strtolower((self::$router->getMethodPrefix() != "" ? self::$router->getMethodPrefix() . '_' : '') . self::$router->getAction());
    
            if(method_exists($controller_class, $controller_method)){
                $controller_obj = new $controller_class();
                $view_path = $controller_obj->$controller_method();
    
                $view_obj = new View($controller_obj->getData(), $view_path);
                $content = $view_obj->render();
            }else{
                throw new Exception("Called method does not exists!");
            }
    
            //layout
            $route_path = self::getRouter()->getRoute();
            $layout = ROOT . '/views/layout/' . $route_path . '.phtml';
            $layout_view_obj = new View(compact('content'), $layout);
            echo $layout_view_obj->render();
        }
    
        public static function redirect($uri){
            print("<script>window.location.href='{$uri}'</script>");
            exit();
        }
    }