簡體   English   中英

無法理解Zend Framework中的MVC控制器

[英]Can't Understand Controllers of MVC in Zend Framework

我是php5和Zend Framework的新手,並且正在使用Zend Studio。 我已經閱讀了許多文檔,但是我仍然無法理解Zend中的控制器背后的概念。

簡而言之,我正在嘗試開發一個用於處理帳戶的小型Web應用程序。 我尚未對默認的index.php文件進行任何更改。 這里是:

<?php

// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

// Define application environment
defined('APPLICATION_ENV')
||define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv ('APPLICATION_ENV'):    'production'));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
       realpath(APPLICATION_PATH . '/../library'),
       get_include_path(),
)));

/* function _initView()
{
   $view = new Zend_View();
   $view->addScriptPath(APPLICATION_PATH . '/views/scripts/');
} */



/** Zend_Application */
require_once 'Zend/Application.php';

// Create application, bootstrap, and run
$application = new Zend_Application(
       APPLICATION_ENV,
       APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap()
->run(); 

這是我的IndexController.php

<?php

class IndexController extends Zend_Controller_Action
{

public function init()
{
    /* Initialize action controller here */
}

 public function indexAction()
 {

 }

}

我也沒有在那里做任何更改,因為我聽不懂這個概念。

我的index.phtml:

<html>
<style>
</style>

<body>
<img alt="" src="http://localhost/Accounts/application/views/scripts/images/logo.png">
<div id="text" >
<h1>Welcome</h1><br><hr>
<h4>Please Log In To View The Main Page</h4></div><br><br><br>
<form action="main/main" method="post"><center><table>
<tr>
<td>User Name  :</td> <td><input type="text" name="uname"/></td>
</tr>
<tr>
<td>Passowrd   :</td> <td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td><center><input type="submit" value="Log In"/></center></td> <td><center><input type="reset" value="Cancel"/></center></td>
</tr>
</table></center></form>
</body>
</html>

**請注意,我已指定

<form action="main/main">

轉到下一頁,即“ main.phtml”。 但這是行不通的。

這是我的MainController.php:

<?php
require_once ('library/Zend/Controller/Action.php');

class MainController extends Zend_Controller_Action {

public function init()
{
    /* Initialize action controller here */
}

public function mainAction()
{
    include 'views/scripts/main/main.phtml';
}
}

在上述控制器中,如果我指定,

include 'views/scripts/main/main.phtml';

是否,它的作用相同。 在瀏覽器上,當我嘗試登錄時什么都沒有顯示。

由於我尚未為登錄指定任何條件,因此我認為應該顯示main.phtml。

這里是:

<html xmlns="http://www.w3.org/1999/xhtml" lang = "en">
<style>
</style>

<head>
    <meta name="keywords" content="" /></meta>
    <meta name="description" content="" /></meta>
    <link rel="shortcut icon" href="http://localhost/Accounts/application/views/scripts/images/favicon.ico" >
    <title>Accounts Handling</title>
</head>

<body>
    <div id="header"></div>
    <div id="main">
        <div id="menu">
        <?php include ('C:\wamp\www\Accounts\application\views\scripts\header\header.php');?>
        </div>
        <div id="content">  
            <center><img src="http://localhost/Accounts/application/views/scripts/images/accounts.jpg" alt="image" height=600px width=550px/></center>  
        </div>
        <div>
        <?php include ('C:\wamp\www\Accounts\application\views\scripts\footer\footer.php');?>
        </div>
    </div>
</body>
</html>

我的代碼有什么問題? 為什么不起作用? 我需要了解的是這些控制器的工作方式。 它們如何鏈接視圖?

首先,您的應用程序可以正常工作嗎? 導航到http://localhost/accounts/public/index時是否獲得索引頁面?還是出現錯誤? 如果遇到錯誤,則需要修復PHP / ZF環境

其次,我建議您為應用程序配置虛擬主機 ,以使導航更加容易。 您將擁有類似於http://accounts/mainhttp://localhost/accounts/public/main而不是http://localhost/accounts/public/main

顯示頁面的問題可能是您根本沒有導航到正確的URL。

現在是您的基本問題。

控制器概念 ...

將MVC應用程序(特別是Zend Framework)中的控制器視為一種數據流量管理器。 控制器是將網頁(視圖)粘合到模型(數據)的控制器。 控制器最通常用於從用戶那里獲取數據(即表單),過濾和驗證該數據,然后將其傳遞給模型以進行進一步處理,或者保存在數據庫或其他存儲中。 它也以另一種方式起作用。 從模型中獲取數據,並准備將其呈現給用戶。

這是一個僅顯示列表用戶的簡單控制器操作的示例:

//navigate to http://myapp/user/list where myapp is the base url, user is the controller
// and list is the action
class UserController extends Zend_Controller_Action{

    public function listAction() { //declare action in camel case
            $currentUsers = Application_Model_DbTable_User::getUsers();//get data from database via model
            if ($currentUsers->count() > 0) {
                $this->view->users = $currentUsers; //send list of users to the view
            } else {
                $this->view->users = NULL;
            }
        }
    }

並顯示此用戶列表,則查看腳本可能類似於:

<!-- list.phmtl at application/views/scripts/user -->
h2>Current Users</h2>
<?php if ($this->users != null) : ?>
    <table class='spreadsheet' cellpadding='0' cellspacing='0'>
        <tr>
            <th>Links</th>
            <th>Last Name</th>
            <th>First Name</th>
            <th>Username</th>
            <th>Role</th>
            <th>
        </tr>
        <?php echo $this->partialLoop('_user-row.phtml', $this->users); ?>
    </table>
<?php else : ?>
    <p>You do not have any users yet.</p>
<?php endif ?>
<p><a href='/user/create'>Create a new user</a></p>

ZF中的partail是一些腳本,使您可以循環使用指定的數據位遍歷同一代碼,在這種情況下,每行用戶將由這幾行代碼顯示。 傾向於替換一些foreach循環的實例。

<!-- the patial _user_row.phtml -->
<tr>
    <td class="links">
        <a href='/page/edit/id/<?php echo $this->id ?>'>Update</a>
        <a href='/page/delete/id/<?php echo $this->id ?>'>Delete</a>
    </td>
    <td><?php echo $this->name ?></td>
</tr>

為了完整起見,我將包括提供數據的模型的一部分:

class Application_Model_DbTable_User extends Zend_Db_Table_Abstract
{
    protected $_name = 'users';

 public static function getUsers() {
        $userModel = new self();
        $select = $userModel->select();
        $select->order(array('last_name', 'first_name'));
        return $userModel->fetchAll($select);
    }
}


我意識到這里的答案有點簡單,因為控制器可以根據應用程序承擔許多角色,它們在大多數應用程序中的主要作用是數據管理和視圖准備。

我了解將您的頭纏住可能有多難,我不久前就經歷了這一過程。 Rob Allens的ZF 1.x教程是一個很好的起點。

另外,您可能希望在開始時對Zend Studio有所警惕,它似乎在項目創建過程中做了一些與Zend_Tool創建項目時所做的事情有所不同(我認為可以在選項中更改此行為),因此Zend studio生成的代碼可能與教程中的代碼不完全相同。

代碼段來自Book Pro Zend Framework Techniques

我希望這會提供一些指導和幫助...

PS如果您已正確安裝和配置ZF,則幾乎永遠不會使用include語句。 如果您必須包含ZF中的任何內容,則您的配置有問題(可能是您的php包含路徑)

[編輯]

要更正500服務器錯誤,您可以檢查以下幾件事:

在您的Apache配置httpd.conf確保未注釋此行LoadModule rewrite_module modules/mod_rewrite.so

在同一.conf文件中,確保您的localhost目錄的目錄條目具有以下設置:

<Directory "C:\Zend\Apache2/htdocs"><--- YOUR DIRECTORY
    ...truncated as the following is the important part
    Options Indexes FollowSymLinks <---IMPORTANT FOLLOWSYMLINKS IS REQUIRED FOR ZF
    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    AllowOverride All<---IMPORTANT, THIS ALLOWS .HTACCESS TO WORK
    #
    # Controls who can get stuff from this server.
    #
    Order allow,deny
    Allow from all
</Directory>

希望這可以解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM