Rozdział 7. Zend_Controller

Spis treści

7.1. Szybki start z klasą Zend_Controller
7.1.1. Wprowadzenie
7.1.2. Szybki start
7.1.2.1. Utwórz strukturę katalogów
7.1.2.2. Ustaw główną ścieżkę serwera
7.1.2.3. Ustaw reguły przepisania
7.1.2.4. Utwórz plik ładujący
7.1.2.5. Utwórz domyślny kontroler akcji
7.1.2.6. Utwórz własny skrypt widoku
7.1.2.7. Utwórz kontroler błędu
7.1.2.8. Zobacz stronę!
7.2. Zend_Controller Basics
7.3. The Front Controller
7.3.1. Overview
7.3.2. Primary Methods
7.3.2.1. getInstance()
7.3.2.2. setControllerDirectory() and addControllerDirectory
7.3.2.3. addModuleDirectory() and getModuleDirectory()
7.3.2.4. dispatch()
7.3.2.5. run()
7.3.3. Environmental Accessor Methods
7.3.4. Front Controller Parameters
7.3.5. Subclassing the Front Controller
7.4. The Request Object
7.4.1. Introduction
7.4.2. HTTP Requests
7.4.2.1. Accessing Request Data
7.4.2.2. Base Url and Subdirectories
7.4.2.3. Determining the Request Method
7.4.2.4. Detecting AJAX Requests
7.4.3. Subclassing the Request Object
7.5. The Standard Router
7.5.1. Introduction
7.5.2. Using a router
7.5.3. Basic Rewrite Router operation
7.5.4. Default routes
7.5.5. Base URL and subdirectories
7.5.6. Route Types
7.5.6.1. Zend_Controller_Router_Route
7.5.6.1.1. Variable defaults
7.5.6.1.2. Variable requirements
7.5.6.2. Zend_Controller_Router_Route_Static
7.5.6.3. Zend_Controller_Router_Route_Regex
7.5.6.4. Zend_Controller_Router_Route_Hostname
7.5.6.4.1. Hostname routes via Zend_Config
7.5.7. Using Zend_Config with the RewriteRouter
7.5.8. Subclassing the Router
7.6. The Dispatcher
7.6.1. Overview
7.6.2. Subclassing the Dispatcher
7.7. Action Controllers
7.7.1. Wprowadzenie
7.7.2. Inicjalizacja obiektu
7.7.3. Metody Pre-Dispatch oraz Post-Dispatch
7.7.4. Metody dostępowe
7.7.5. Integracja z widokiem
7.7.5.1. Inicjowanie obiektu widoku
7.7.5.2. Renderowanie widoków
7.7.6. Metody narzędziowe
7.7.7. Rozszerzanie klasy kontrolera akcji
7.8. Action Helpers
7.8.1. Introduction
7.8.2. Helper Initialization
7.8.3. The Helper Broker
7.8.4. Built-in Action Helpers
7.8.4.1. ActionStack
7.8.4.2. AutoComplete
7.8.4.2.1. AutoCompletion with Dojo
7.8.4.2.2. AutoCompletion with Scriptaculous
7.8.4.3. ContextSwitch and AjaxContext
7.8.4.3.1. Default Contexts Available
7.8.4.3.2. Creating Custom Contexts
7.8.4.3.3. Setting Contexts Per Action
7.8.4.3.4. Initializing Context Switching
7.8.4.3.5. Additional Functionality
7.8.4.3.6. AjaxContext Functionality
7.8.4.4. FlashMessenger
7.8.4.4.1. Introduction
7.8.4.4.2. Basic Usage Example
7.8.4.5. JSON
7.8.4.6. Redirector
7.8.4.6.1. Introduction
7.8.4.6.2. Basic Usage Examples
7.8.4.7. ViewRenderer
7.8.4.7.1. Introduction
7.8.4.7.2. API
7.8.4.7.3. Basic Usage Examples
7.8.4.7.4. Advanced Usage Examples
7.8.5. Writing Your Own Helpers
7.9. The Response Object
7.9.1. Usage
7.9.2. Manipulating Headers
7.9.3. Named Segments
7.9.4. Testing for Exceptions in the Response Object
7.9.5. Subclassing the Response Object
7.10. Wtyczki
7.10.1. Wprowadzenie
7.10.2. Pisanie wtyczek
7.10.3. Użycie wtyczek
7.10.4. Wtyczki dołączone do standardowej dystrybucji
7.10.4.1. ActionStack
7.10.4.2. Zend_Controller_Plugin_ErrorHandler
7.10.4.2.1. Using the ErrorHandler as a 404 Handler
7.10.4.2.2. Handling Previously Rendered Output
7.10.4.2.3. Plugin Usage Examples
7.10.4.2.4. Error Controller Example
7.11. Użycie konwencjonalnej modularnej struktury katalogów
7.11.1. Wprowadzenie
7.11.2. Określanie ścieżek kontrolera modułów
7.11.3. Dopasowanie tras do modułów
7.11.4. Moduł lub globalny domyślny kontroler
7.12. Wyjątki MVC
7.12.1. Wprowadzenie
7.12.2. W jaki sposób możesz obsługiwać wyjątki?
7.12.3. Wyjątki MVC które możesz napotkać
7.13. Migracja z poprzednich wersji
7.13.1. Migracja z wersji 1.5.x do 1.6.0 lub nowszej
7.13.1.1. Zmiany w interfejsie obiektu uruchamiającego
7.13.2. Migracja z wersji 1.0.x do 1.5.0 lub nowszej
7.13.3. Migracja z wersji 0.9.3 do 1.0.0RC1 lub nowszej
7.13.4. Migracja z wersji 0.9.2 do 0.9.3 lub nowszej
7.13.5. Migracja z wersji 0.6.0 do 0.8.0 lub nowszej
7.13.6. Migracja z wersji 0.2.0 lub z poprzednich do 0.6.0

7.1. Szybki start z klasą Zend_Controller

7.1.1. Wprowadzenie

Klasa Zend_Controller jest sercem systemu MVC biblioteki Zend Framework. MVC oznacza Model-Widok-Kontroler i jest wzorcem projektowym mającym na celu oddzielenie logiki aplikacji od logiki wyświetlania. Klasa Zend_Controller_Front implementuje wzorzec projektowy kontrolera frontowego. Wszystkie żądania są przechwytywane przez kontroler frontowy i na podstawie adresu URL uruchamiany jest odpowiedni kontroler akcji.

The Zend_Controller system was built with extensibility in mind, either by subclassing the existing classes, writing new classes that implement the various interfaces and abstract classes that form the foundation of the controller family of classes, or writing plugins or action helpers to augment or manipulate the functionality of the system.

7.1.2. Szybki start

If you need more in-depth information, see the following sections. If you just want to get up and running quickly, read on.

7.1.2.1. Utwórz strukturę katalogów

Pierwszym krokiem jest utworzenie struktury katalogów. Typowa struktura wygląda w taki sposób:

application/
    controllers/
        IndexController.php
    models/
    views/
        scripts/
            index/
                index.phtml
        helpers/
        filters/
html/
    .htaccess
    index.php

            

7.1.2.2. Ustaw główną ścieżkę serwera

W swoim serwerze www, ustaw główną ścieżkę serwera na katalog html znajdujący się w powyższej przykładowej strukturze katalogów.

7.1.2.3. Ustaw reguły przepisania

Zedytuj plik html/.htaccess aby wyglądał w taki sposób:

RewriteEngine on
RewriteRule !\.(js|ico|gif|jpg|png|css)$ index.php

            

The above rules will route any non-resource (images, stylesheets) requests to the front controller. If there are other extensions you wish to exclude from the front controller (PDFs, text files, etc), add their extensions to the switch, or create your own rewrite rules.

[Notatka] Notatka

Powyższe reguły przepisania przygotowane sa dla serwera Apache; aby zobaczyć przykładowe reguły dla innych serwerów, zobacz dokumentację routera.

7.1.2.4. Utwórz plik ładujący

Plik ładujący jest miejscem, przez którze przechodzą wszystkie żądania -- w tym przypadku jest to -- html/index.php. Otwórz plik html/index.php w dowolnym edytorze i dodaj poniższy kod:

Zend_Controller_Front::run('/path/to/app/controllers');

            

Utworzy to egzemplarz kontrolera frontowego i go uruchomi, co spowoduje przekazanie żądań do kontrolerów akcji.

7.1.2.5. Utwórz domyślny kontroler akcji

Before discussing action controllers, you should first understand how requests are routed in Zend Framework. By default, the first segment of a URL path maps to a controller, and the second to an action. For example, given the URL http://framework.zend.com/roadmap/components, the path is /roadmap/components, which will map to the controller roadmap and the action components. If no action is provided, the action index is assumed, and if no controller is provided, the controller index is assumed (following the Apache convention that maps a DirectoryIndex automatically).

Zend_Controller's dispatcher then takes the controller value and maps it to a class. By default, it Title-cases the controller name and appends the word Controller. Thus, in our example above, the controller roadmap is mapped to the class RoadmapController.

Similarly, the action value is mapped to a method of the controller class. By default, the value is lower-cased, and the word Action is appended. Thus, in our example above, the action components becomes componentsAction, and the final method called is RoadmapController::componentsAction().

Idąc dalej, utwórzmy teraz domyślny kontroler akcji i metodę akcji. Jak wspomniano wcześniej, domyślna nazwa kontrolera oraz akcji to index. Otwórz w edytorze plik application/controllers/IndexController.php, i dodaj poniższy kod:

class IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
    }
}

            

By default, the ViewRenderer action helper is enabled. What this means is that by simply defining an action method and a corresponding view script, you will immediately get content rendered. By default, Zend_View is used as the View layer in the MVC. The ViewRenderer does some magic, and uses the controller name (e.g., index) and the current action name (e.g., index) to determine what template to pull. By default, templates end in the .phtml extension, so this means that, in the above example, the template index/index.phtml will be rendered. Additionally, the ViewRenderer automatically assumes that the directory views at the same level as the controller directory will be the base view directory, and that the actual view scripts will be in the views/scripts/ subdirectory. Thus, the template rendered will be found in application/views/scripts/index/index.phtml.

7.1.2.6. Utwórz własny skrypt widoku

As mentioned in the previous section, view scripts are found in application/views/scripts/; the view script for the default controller and action is in application/views/scripts/index/index.phtml. Create this file, and type in some HTML:

<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Pierwsza aplikacja Zend Framework</title>
</head>
<body>
    <h1>Witaj!</h1>
</body>
</html>

            

7.1.2.7. Utwórz kontroler błędu

Domyślnie, wtyczka obsługi błędów jest zarejestrowana. Ta wtyczka expects that a controller exists to handle errors. By default, it assumes an ErrorController in the default module with an errorAction method:

class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
    }
}

            

Assuming the already discussed directory layout, this file will go in application/controllers/ErrorController.php. You will also need to create a view script in application/views/scripts/error/error.phtml; sample content might look like:

<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Błąd</title>
</head>
<body>
    <h1>Wystąpił błąd</h1>
    <p>Wystąpił błąd; spróbuj ponownie później.</p>
</body>
</html>

            

7.1.2.8. Zobacz stronę!

With your first controller and view under your belt, you can now fire up your browser and browse to the site. Assuming example.com is your domain, any of the following URLs will get to the page we've just created:

  • http://example.com/

  • http://example.com/index

  • http://example.com/index/index

Teraz jesteś gotowy do tworzenia kolejnych kontrolerów i metod akcji. Gratulacje!