如何在子文件夹PHP中呈现视图

时间:2017-02-01 09:06:40

标签: php

我是MVC的新手,刚开始练习它。我正在创建一个中小型企业网站,并且不想使用任何大型框架,因此我找到了this,到目前为止它工作得很好。我唯一不理解的是如何在子文件夹中渲染视图。

我需要3种药物来显示信息,它们的结构如下:

views
--medicines
----medicine1
------info.php
------forms
--------male.php
--------female.php

这是药物控制器:

<?php

class MedicinesController extends Controller
{
    /**
     * Construct this object by extending the basic Controller class
     */
    public function __construct()
    {
        parent::__construct();

        Auth::checkAuthentication();
    }

    /**
     * Handles what happens when user moves to URL/medicines/index
     **/
    public function index()
    {
        $this->View->render('medicines/index');
    }

    /**
     * Handles what happens when user moves to URL/medicines/medicine1
     **/
    public function medicine1()
    {
        $this->View->render('medicines/medicine/info', array(
            'files' => FilesModel::getMedicineFiles())
        );
    }

    /**
     * Handles what happens when user moves to URL/medicines/medicine1/forms/male
     **/
    public function male()
    {
        $this->View->render('medicines/imnovid/forms/male');
    }

}

这是处理控制器的类:

/**
 * Class Application
 * The heart of the application
 */
class Application
{
    /** @var mixed Instance of the controller */
    private $controller;

    /** @var array URL parameters, will be passed to used controller-method */
    private $parameters = array();

    /** @var string Just the name of the controller, useful for checks inside the view ("where am I ?") */
    private $controller_name;

    /** @var string Just the name of the controller's method, useful for checks inside the view ("where am I ?") */
    private $action_name;

    /**
     * Start the application, analyze URL elements, call according controller/method or relocate to fallback location
     */
    public function __construct()
    {
        // create array with URL parts in $url
        $this->splitUrl();

        // creates controller and action names (from URL input)
        $this->createControllerAndActionNames();

        // does such a controller exist ?
        if (file_exists(Config::get('PATH_CONTROLLER') . $this->controller_name . '.php')) {

            // load this file and create this controller
            // example: if controller would be "car", then this line would translate into: $this->car = new car();
            require Config::get('PATH_CONTROLLER') . $this->controller_name . '.php';
            $this->controller = new $this->controller_name();

            // check for method: does such a method exist in the controller ?
            if (method_exists($this->controller, $this->action_name)) {
                if (!empty($this->parameters)) {
                    // call the method and pass arguments to it
                    call_user_func_array(array($this->controller, $this->action_name), $this->parameters);
                } else {
                    // if no parameters are given, just call the method without parameters, like $this->index->index();
                    $this->controller->{$this->action_name}();
                }
            } else {
                // load 404 error page
                require Config::get('PATH_CONTROLLER') . 'ErrorController.php';
                $this->controller = new ErrorController;
                $this->controller->error404();
            }
        } else {
            // load 404 error page
            require Config::get('PATH_CONTROLLER') . 'ErrorController.php';
            $this->controller = new ErrorController;
            $this->controller->error404();
        }
    }

    /**
     * Get and split the URL
     */
    private function splitUrl()
    {
        if (Request::get('url')) {

            // split URL
            $url = trim(Request::get('url'), '/');
            $url = filter_var($url, FILTER_SANITIZE_URL);
            $url = explode('/', $url);

            // put URL parts into according properties
            $this->controller_name = isset($url[0]) ? $url[0] : null;
            $this->action_name = isset($url[1]) ? $url[1] : null;

            // remove controller name and action name from the split URL
            unset($url[0], $url[1]);

            // rebase array keys and store the URL parameters
            $this->parameters = array_values($url);
        }
    }

    /**
     * Checks if controller and action names are given. If not, default values are put into the properties.
     * Also renames controller to usable name.
     */
    private function createControllerAndActionNames()
    {
        // check for controller: no controller given ? then make controller = default controller (from config)
        if (!$this->controller_name) {
            $this->controller_name = Config::get('DEFAULT_CONTROLLER');
        }

        // check for action: no action given ? then make action = default action (from config)
        if (!$this->action_name or (strlen($this->action_name) == 0)) {
            $this->action_name = Config::get('DEFAULT_ACTION');
        }

        // rename controller name to real controller class/file name ("index" to "IndexController")
        $this->controller_name = ucwords($this->controller_name) . 'Controller';
    }
}

配置

/**
 * Configuration for: Folders
 * Usually there's no reason to change this.
 */
'PATH_CONTROLLER' => realpath(dirname(__FILE__).'/../../') . '/application/controller/',
'PATH_VIEW' => realpath(dirname(__FILE__).'/../../') . '/application/view/',

/**
 * Configuration for: Default controller and action
 */
'DEFAULT_CONTROLLER' => 'index',
'DEFAULT_ACTION' => 'index',

渲染

public function render($filename, $data = null)
{
    if ($data) {
        foreach ($data as $key => $value) {
            $this->{$key} = $value;
        }
    }

    require Config::get('PATH_VIEW') . '_templates/header.php';
    require Config::get('PATH_VIEW') . $filename . '.php';
    require Config::get('PATH_VIEW') . '_templates/footer.php';
}

修改

如果我var_dump();我得到了这个输出:

    D:\Programs\wamp64\www\ermp.ee\application\core\Application.php:84:
object(Application)[3]
  private 'controller' => null
  private 'parameters' => 
    array (size=2)
      0 => string 'forms' (length=5)
      1 => string 'male' (length=4)
  private 'controller_name' => string 'medicines' (length=9)
  private 'action_name' => string 'imnovid' (length=7)

4 个答案:

答案 0 :(得分:4)

简单网址

当您访问http://ermp.ee/medicines/时,由于以下行,它会呈现application/view/medicines/index.php文件:

$this->View->render('medicines/index');

当您访问http://ermp.ee/medicines/medicine1/forms/male时,由于

,它会使用application/view/medicines/info.php param呈现files个文件
$this->View->render('medicines/medicine/info'... 

您将视图文件名直接传递给Viewformsmale存储在Application的私有财产parameters中。

在这种情况下,controller_nameMedicinesControlleraction_namemedicine1

包含male

的网址

当您访问http://ermp.ee/medicines/male时,controller_nameMedicinesControlleraction_namemale,但由于以下内容,所呈现的视图为medicines/imnovid/forms/male.php行:

$this->View->render('medicines/imnovid/forms/male');

无论视图的路径是什么,action_name都来自URI。根据动作名称使用路径只是一种惯例,您可以自由地呈现您想要的任何内容。

答案 1 :(得分:3)

从我在您链接的Github存储库中读取的内容,如果要呈现存储在子目录中的视图,您应该能够通过在传递给render()的文件名中使用正斜杠来实现

在控制器中,要渲染info.php,您可以调用

$this->View->render('medicines/medicine1/info');

答案 2 :(得分:0)

从主视图中渲染子视图。就像这样:

行动中:

$formView = $user->gender == 1 ? 'female' : 'male';

在视图中:

<?= $this->render("/form/$formView.php") ?>

答案 3 :(得分:-1)

试试这个,

<html>

    <head>
        <title>help</title>
    </head>

    <body>
        <?php

            if(isset($_POST['update'])) {
                $dbhost = 'localhost';
                $dbuser = '*********';
                $dbpass = '*****';
                $conn = mysqli_connect($dbhost, $dbuser, $dbpass);
                if(! $conn ) {
                   die('Could not connect: ' . mysqli_error());
                }
                $Userid = $_POST['UserID'];
                $TableID = $_POST['tableID'];
                $Life_points = $_POST['Life_points'];
                $xp_points = $_POST['xp_points'];
                $sql = "UPDATE points SET TableID = " . $TableID . " WHERE UserID = ". $Userid . " AND life_points = " . $Life_points . " AND xp_points= " . $xp_points;
                mysqli_select_db('womath');

                $retval = mysqli_query(  $conn, $sql );
                <?php echo $_SERVER['PHP_SERVER'] ?>            

                if(! $retval ) {
                    die('Could not update data: ' . mysqli_error());
                }
                echo "Updated data successfully\n";
                mysqli_close($conn);
                } else {
                ?>
                    <form method = "post" action = "<?php $_PHP_SELF ?>">
                        <table width = "400" border =" 0" cellspacing = "1" cellpadding = "2">
                            <tr>
                                <td width = "100">UserID</td>
                                <td><input name = "UserID" type = "number" id = "UserID"></td>
                            </tr>
                            <tr>
                                <td width = "100">TableID</td>
                                <td><input name = "TableID" type = "number" id = "TableID"></td>
                            </tr>
                            <tr>
                                <td width = "100">life_points</td>
                                <td><input name = "life_points" type = "number" id = "life_points"></td>
                            </tr>
                            <tr>
                               <td width = "100">xp_points</td>
                               <td><input name = "xp_points" type = "number" id = "xp_points"></td>
                            </tr>
                            <tr>
                                <td width = "100"> </td>
                                <td> </td>
                            </tr>
                            <tr>
                                <td width = "100"> </td>
                                <td><input name = "update" type = "submit" id = "update" value = "Update"></td>
                            </tr>
                       </table>
                   </form>
               <?php 
            } 
        ?>

    </body>
</html>