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

时间:2012-07-07 07:53:55

标签: php zend-framework zend-studio

我是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>

我的代码有什么问题?为什么这不起作用?我需要了解的是这些控制器是如何工作的。他们如何链接视图?

1 个答案:

答案 0 :(得分:4)

首先,您的应用程序是否正常工作?当您导航到http://localhost/accounts/public/index或者出现错误时,您是否获得了索引页面?如果您收到错误,则需要修复PHP/ZF environment

其次,我建议您为应用程序配置virtual host,以便更轻松地进行导航。您将拥有http://accounts/main而非http://localhost/accounts/public/main的网址。

显示页面的问题可能是您没有导航到正确的网址。

现在问你的基本问题。?

The controller concept ...

将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's ZF 1.x tutorial

此外,您可能希望在开始时对Zend Studio保持警惕,它似乎在项目创建过程中做了一些与Zend_Tool创建项目时所做的事情不同(我认为这种行为)可以在选项中更改)因此Zend studio生成的代码可能与教程中的代码不完全相同。

代码段来自本书 Pro Zend Framework Techniques

我希望这会提供一些指导和帮助...

P.S。如果您已正确安装和配置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>

希望这可以解决您的问题。