Crie Seu Projeto
Para criar seu projeto, você primeiro deve baixar e extrair o Zend Framework.
Instale o Zend Framework
A maneira mais fácil de obter o Zend Framework junto com uma pilha
PHP completa é através da instalação do Zend Server. O
Zend Server tem instaladores nativos para Mac OSX, Windows, Fedora Core e Ubuntu, bem
como um pacote de instalação universal compatível com a maioria das distribuições Linux.
Depois que você tiver instalado o Zend Server, os arquivos Framework podem ser
encontrados em /usr/local/zend/share/ZendFramework no Mac OSX e
Linux, e em C:\Program Files\Zend\ZendServer\share\ZendFramework no
Windows. O include_path já estará configurado para incluir o Zend
Framework.
Alternadamente, você pode fazer o Download da última versão do Zend
Framework e extrair os conteúdos; faça nota de onde você fez isso.
Opcionalmente, você pode adicionar o caminho do arquivo para o subdiretório
library/ para a configuração include_path do
seu php.ini.
É isso! O Zend Framework agora está instalado e pronto para uso.
Crie seu ProjetoFerramenta de Linha de Comando zf
Na instalação do Zend Framework tem um subdiretório bin/,
contendo os scripts zf.sh e zf.bat para
usuários baseados em Unix e Windows, respectivamente. Faça nota do caminho absoluto
para este script.
Onde quer que você veja referências para o comando zf, por favor
substitua o caminho absoluto ao script. Nos sistemas baseados em Unix, você pode
querer usar a funcionalidade de apelido do shell: alias
zf.sh=path/to/ZendFramework/bin/zf.sh.
Se você tiver problemas em configurar a ferramenta de linha de comando
zf, por favor dirija-se
ao manual.
Abra o terminal (no Windows, Iniciar -> Executar, e então use
cmd). Vá até o diretório onde você gostaria de iniciar um projeto.
Depois, use o caminho para o script apropriado, e execute um dos seguintes:
Executando este comando, será criada a estrutura básica do seu site, incluindo seus
controladores e visualizações iniciais. A árvore parece com o seguinte:
Até este ponto, se você não adicionou o Zend Framework para o seu
include_path, nós recomendamos também copiar ou criar um link
simbólico em seu diretório library/. Em qualquer caso, você vai
querer copiar recursivamente ou simbolizar o diretório
library/Zend/ da sua instalação Zend Framework no diretório
library/ do seu projeto. Nos sistemas baseados em Unix, que
pareceriam como um dos seguintes:
Nos sistemas Windows, pode ser mais fácil fazer isso do Explorer.
Agora que o projeto está criado, os artefatos principais para iniciar o entendimento
são a inicialização da aplicação, configuração, controladores de ação e vizualizações.
A Inicialização da Aplicação
A classe Inicialização da Aplicação define quais recursos e
componentes inicializar. Por padrão, o Controlador
Frontal do Zend Framework é inicializado, e ele usa o
application/controllers/ como diretório padrão o qual procura por
controladores de ação (mais sobre isso mais tarde). A classe parece com o seguinte:
As you can see, not much is necessary to begin with.
Como você pode ver, não é necessário muito para iniciar.
Configuração
Enquanto o Zend Framework é em si configuração, muitas vezes você precisa configurar
sua aplicação. A configuração padrão está localizada em
application/configs/application.ini, e contém algumas diretrizes
básicas para configurar seu ambiente PHP (por exemplo, transformar
relatório de erros dentro e fora), indicando o caminho para sua classe inicialização da
aplicação (tão bem como sua classe nome), e o caminho para seus controladores de ação.
Isso parece com o seguinte:
Diversas coisas sobre este arquivo devem ser notadas. Primeiro, quando usar configuração
de estilo INI, você pode referenciar constantes diretamente e
expandi-las; APPLICATION_PATH é na verdade uma constante.
Adicionalmente note que há várias seções definidas: produção, encenação, teste, e
desenvolvimento. As últimas três herdam configurações do ambiente "produção". Este é um
modo eficiente de organizar configurações para assegurar que as configurações
apropriadas são válidas em cada estágio do desenvolvimento da aplicação.
Action Controllers
Your application's action controllers contain your application
workflow, and do the work of mapping your requests to the appropriate models and views.
An action controller should have one or more methods ending in "Action"; these methods
may then be requested via the web. By default, Zend Framework URLs follow the schema
/controller/action, where "controller" maps to the action
controller name (minus the "Controller" suffix) and "action" maps to an action method
(minus the "Action" suffix).
Typically, you always need an IndexController, which is a
fallback controller and which also serves the home page of the site, and an
ErrorController, which is used to indicate things such as
HTTP 404 errors (controller or action not found) and
HTTP 500 errors (application errors).
The default IndexController is as follows:
And the default ErrorController is as follows:
_getParam('error_handler');
switch ($errors->type) {
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
// 404 error -- controller or action not found
$this->getResponse()->setHttpResponseCode(404);
$this->view->message = 'Page not found';
break;
default:
// application error
$this->getResponse()->setHttpResponseCode(500);
$this->view->message = 'Application error';
break;
}
$this->view->exception = $errors->exception;
$this->view->request = $errors->request;
}
}
]]>
You'll note that (1) the IndexController contains no real code,
and (2) the ErrorController makes reference to a "view" property.
That leads nicely into our next subject.
Views
Views in Zend Framework are written in plain old PHP. View scripts
are placed in application/views/scripts/, where they are further
categorized using the controller names. In our case, we have an
IndexController and an ErrorController,
and thus we have corresponding index/ and
error/ subdirectories within our view scripts directory. Within
these subdirectories, you will then find and create view scripts that correspond to each
controller action exposed; in the default case, we thus have the view scripts
index/index.phtml and error/error.phtml.
View scripts may contain any markup you want, and use the <?php
opening tag and ?> closing tag to insert PHP
directives.
The following is what we install by default for the
index/index.phtml view script:
]]>
The error/error.phtml view script is slightly more interesting as
it uses some PHP conditionals:
Zend Framework Default Application
An error occurred
message ?>
env): ?>
Exception information:
Message: exception->getMessage() ?>
Stack trace:
exception->getTraceAsString() ?>
Request Parameters:
request->getParams(), 1) ?>
]]>Create a virtual host
For purposes of this quick start, we will assume you are using the Apache web server. Zend Framework works
perfectly well with other web servers -- including Microsoft Internet Information
Server, lighttpd, nginx, and more -- but most developers should be famililar with Apache
at the minimum, and it provides an easy introduction to Zend Framework's directory
structure and rewrite capabilities.
To create your vhost, you need to know the location of your
httpd.conf file, and potentially where other configuration files
are located. Some common locations:
/etc/httpd/httpd.conf (Fedora, RHEL, and others)
/etc/apache2/httpd.conf (Debian, Ubuntu, and others)
/usr/local/zend/etc/httpd.conf (Zend Server on *nix
machines)
C:\Program Files\Zend\Apache2\conf (Zend Server on Windows
machines)
Within your httpd.conf (or httpd-vhosts.conf
on some systems), you will need to do two things. First, ensure that the
NameVirtualHost is defined; typically, you will set it to a value of
"*:80". Second, define a virtual host:
ServerName quickstart.local
DocumentRoot /path/to/quickstart/public
SetEnv APPLICATION_ENV "development"
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
]]>
There are several things to note. First, note that the DocumentRoot
setting specifies the public subdirectory of our project; this
means that only files under that directory can ever be served directly by the server.
Second, note the AllowOverride, Order, and
Allow directives; these are to allow us to use
htacess files within our project. During development, this is a
good practice, as it prevents the need to constantly restart the web server as you make
changes to your site directives; however, in production, you should likely push the
content of your htaccess file into your server configuration and
disable this. Third, note the SetEnv directive. What we are doing
here is setting an environment variable for your virtual host; this variable will be
picked up in the index.php and used to set the
APPLICATION_ENV constant for our Zend Framework application. In
production, you can omit this directive (in which case it will default to the value
"production") or set it explicitly to "production".
Finally, you will need to add an entry in your hosts file
corresponding to the value you place in your ServerName directive. On
*nix-like systems, this is usually /etc/hosts; on Windows, you'll
typically find it in C:\WINDOWS\system32\drivers\etc. Regardless of
the system, the entry will look like the following:
Start your webserver (or restart it), and you should be ready to go.
Checkpoint
At this point, you should be able to fire up your initial Zend Framework application.
Point your browser to the server name you configured in the previous section; you should
be able to see a welcome page at this point.