2012-07-07 4 views
2

저는 php5 및 Zend Framework의 초보자이며 Zend Studio를 사용하고 있습니다. 많은 문서화 작업을 거쳤지만 젠드의 콘트롤러 개념을 이해할 수는 없습니다.Zend Framework의 MVC 컨트롤러를 이해할 수 없습니다.

간단히 설명하면 계정 처리를위한 작은 웹 응용 프로그램을 개발하려고합니다. 기본 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> 

이 ** 내가 "main.phtml"인 다음 페이지로 이동
<form action="main/main"> 

를 지정했는지 유의하시기 바랍니다. 그러나 이것은 작동하지 않습니다. 내가 지정하는 경우는 동일하게 작동,,,

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

여부 위의 컨트롤러

<?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'; 
} 
} 

:

여기 내 MainController.php입니다. 브라우저에서 로그인을 시도 할 때 아무 것도 표시되지 않습니다.

로그인 기준을 지정하지 않았으므로 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> 

내 코드의 문제점은 무엇입니까? 왜이 기능이 작동하지 않습니까? 내가 이해해야 할 것은 컨트롤러가 어떻게 작동하는지입니다. 뷰를 어떻게 연결합니까?

+0

화면에 표시되지 않는 오류가있는 경우 로그를 확인하는 것이 좋습니다. 또는 화면에 오류가 표시되는지 여부를 결정하는 환경 설정이있을 수 있습니다 (일반적으로 : dev = yes, production = no). – halfer

+0

죄송합니다. "application.config"파일에 대해 "config"파일에 대해 언급 한 적이 있습니까? :-) –

+0

예, 설정 파일 일 가능성이 높습니다. 저는 Zend에서 MVC를 사용하지는 않았지만 데이터베이스 연결 및 화면 상 오류보고와 같은 것을 전환하는 "개발"및 "프로덕션"환경 개념을 갖고 있습니다. – halfer

답변

4

처음에는 응용 프로그램이 전혀 작동합니까? http://localhost/accounts/public/index으로 이동하거나 오류가 발생하면 색인 페이지를 가져 옵니까? 오류가 발생하면 PHP/ZF environment을 수정해야합니다.

둘째, 내비게이션을 더 쉽게하기 위해 응용 프로그램에 virtual host을 구성하는 것이 좋습니다. http://localhost/accounts/public/main 대신 http://accounts/main과 같은 URL을 사용하게됩니다.

페이지를 표시 할 때의 문제는 올바른 URL로 이동하지 않았을 수 있습니다.

기본 질문에요.?

The controller concept

... 데이터 트래픽 관리자의 일종으로서 MVC 어플리케이션 (구체적 젠드 프레임 워크)의 컨트롤러

생각한다. 컨트롤러는 웹 페이지 (보기)를 모델 (데이터)에 붙이는 역할을합니다. 컨트롤러는 가장 일반적으로 사용자로부터 데이터를 가져 오는 데 사용됩니다 (즉,양식)을 작성한 후 해당 데이터를 필터링하고 유효성을 검증 한 다음 추가 처리를 위해 모델에 전달하거나 데이터베이스 또는 기타 저장 영역에 지속되도록하십시오. 그것은 다른 방법으로도 작동합니다. 모델에서 데이터를 가져 와서 사용자에게 표시 할 수 있도록 준비하십시오.

//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_Tool가하는 것과 다른 프로젝트 생성시 어떤 일을 할 것 같다 (나는이 문제가 될 수 있다고 생각 옵션이 변경되었으므로) Zend Studio에서 생성 된 코드는 자습서와 완전히 동일하지 않을 수 있습니다.

코드 조각은 ... 나는이 몇 가지 방향을 제시하고 도움을 희망 도서Pro Zend Framework Techniques

에서

P.S. 있습니다 ZF를 올바르게 설치하고 구성한 경우 include 문을 거의 사용하지 않습니다. 당신은 ZF에서 아무것도를 포함해야하는 경우 당신은 당신이 확인할 수 있습니다 몇 가지가있다,

[편집]

500 서버 오류를 해결하려면 구성 (아마 PHP를 포함 경로)에 문제가 :

아파치 설정에서 httpd.conf이 라인이 LoadModule rewrite_module modules/mod_rewrite.so으로되어 있는지 확인하십시오.

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

는 희망이 당신의 문제가 해결됩니다 : 당신이 디렉토리가이 다음과 같은 설정이 로컬 호스트에 대한


는 동일한의 .conf 파일에서 확인 디렉토리 항목을 확인하십시오.

+0

주셔서 감사 정보에 ​​대한 많은 .... 내가 이동하면 HTTP 로는 : // localhost를/계정/공공/인덱스 일했다. 왜 내가 이해할 수 없는지, 내 응용 프로그램의 다음 페이지로 이동할 수없는 이유는 무엇입니까? 설명을 주셔서 감사합니다. :-) –

+0

'localhost'로 이동할 때 어떤 종류의 오류가 발생합니까?/accounts/main/main'? 내용이 없거나 오류가있는 빈 화면이 나타나면이 행을'/ public'의 .htaccess 파일에 추가하십시오 :'SetEnv APPLICATION_ENV development' – RockyFord

+0

제공 한 회선을 추가하려고했습니다. 하지만 500 오류가 발생하고 "서버에 내부 오류 또는 잘못된 구성이 발생하여 요청을 완료하지 못했습니다."라고 표시됩니다. 도움을 주셔서 감사합니다 .-) –