quickstart-create-project.xml 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- EN-Revision: 24249 -->
  3. <!-- Reviewed: no -->
  4. <sect1 id="learning.quickstart.create-project">
  5. <title>Crie Seu Projeto</title>
  6. <para>
  7. Para criar seu projeto, você primeiro deve baixar e extrair o Zend Framework.
  8. </para>
  9. <sect2 id="learning.quickstart.create-project.install-zf">
  10. <title>Instale o Zend Framework</title>
  11. <para>
  12. A maneira mais fácil de obter o Zend Framework junto com uma pilha
  13. <acronym>PHP</acronym> completa é através da instalação do <ulink
  14. url="http://www.zend.com/en/products/server-ce/downloads">Zend Server</ulink>. O
  15. Zend Server tem instaladores nativos para Mac OSX, Windows, Fedora Core e Ubuntu, bem
  16. como um pacote de instalação universal compatível com a maioria das distribuições Linux.
  17. </para>
  18. <para>
  19. Depois que você tiver instalado o Zend Server, os arquivos Framework podem ser
  20. encontrados em <filename>/usr/local/zend/share/ZendFramework</filename> no Mac OSX e
  21. Linux, e em <filename>C:\Program Files\Zend\ZendServer\share\ZendFramework</filename> no
  22. Windows. O <constant>include_path</constant> já estará configurado para incluir o Zend
  23. Framework.
  24. </para>
  25. <para>
  26. Alternadamente, você pode fazer o <ulink
  27. url="http://framework.zend.com/download/latest">Download da última versão do Zend
  28. Framework</ulink> e extrair os conteúdos; faça nota de onde você fez isso.
  29. </para>
  30. <para>
  31. Opcionalmente, você pode adicionar o caminho do arquivo para o subdiretório
  32. <filename>library/</filename> para a configuração <constant>include_path</constant> do
  33. seu <filename>php.ini</filename>.
  34. </para>
  35. <para>
  36. É isso! O Zend Framework agora está instalado e pronto para uso.
  37. </para>
  38. </sect2>
  39. <sect2 id="learning.quickstart.create-project.create-project">
  40. <title>Crie seu Projeto</title>
  41. <note>
  42. <title>Ferramenta de Linha de Comando zf</title>
  43. <para>
  44. Na instalação do Zend Framework tem um subdiretório <filename>bin/</filename>,
  45. contendo os scripts <filename>zf.sh</filename> e <filename>zf.bat</filename> para
  46. usuários baseados em Unix e Windows, respectivamente. Faça nota do caminho absoluto
  47. para este script.
  48. </para>
  49. <para>
  50. Onde quer que você veja referências para o comando <command>zf</command>, por favor
  51. substitua o caminho absoluto ao script. Nos sistemas baseados em Unix, você pode
  52. querer usar a funcionalidade de apelido do shell: <command>alias
  53. zf.sh=path/to/ZendFramework/bin/zf.sh</command>.
  54. </para>
  55. <para>
  56. Se você tiver problemas em configurar a ferramenta de linha de comando
  57. <command>zf</command>, por favor dirija-se
  58. <link linkend="zend.tool.framework.clitool"> ao manual</link>.
  59. </para>
  60. </note>
  61. <para>
  62. Abra o terminal (no Windows, <command>Iniciar -> Executar</command>, e então use
  63. <command>cmd</command>). Vá até o diretório onde você gostaria de iniciar um projeto.
  64. Depois, use o caminho para o script apropriado, e execute um dos seguintes:
  65. </para>
  66. <programlisting language="shell"><![CDATA[
  67. % zf create project quickstart
  68. ]]></programlisting>
  69. <para>
  70. Executando este comando, será criada a estrutura básica do seu site, incluindo seus
  71. controladores e visualizações iniciais. A árvore parece com o seguinte:
  72. </para>
  73. <programlisting language="text"><![CDATA[
  74. quickstart
  75. |-- application
  76. | |-- Bootstrap.php
  77. | |-- configs
  78. | | `-- application.ini
  79. | |-- controllers
  80. | | |-- ErrorController.php
  81. | | `-- IndexController.php
  82. | |-- models
  83. | `-- views
  84. | |-- helpers
  85. | `-- scripts
  86. | |-- error
  87. | | `-- error.phtml
  88. | `-- index
  89. | `-- index.phtml
  90. |-- library
  91. |-- public
  92. | |-- .htaccess
  93. | `-- index.php
  94. `-- tests
  95. |-- application
  96. | `-- bootstrap.php
  97. |-- library
  98. | `-- bootstrap.php
  99. `-- phpunit.xml
  100. ]]></programlisting>
  101. <para>
  102. Até este ponto, se você não adicionou o Zend Framework para o seu
  103. <constant>include_path</constant>, nós recomendamos também copiar ou criar um link
  104. simbólico em seu diretório <filename>library/</filename>. Em qualquer caso, você vai
  105. querer copiar recursivamente ou simbolizar o diretório
  106. <filename>library/Zend/</filename> da sua instalação Zend Framework no diretório
  107. <filename>library/</filename> do seu projeto. Nos sistemas baseados em Unix, que
  108. pareceriam como um dos seguintes:
  109. </para>
  110. <programlisting language="shell"><![CDATA[
  111. # Symlink:
  112. % cd library; ln -s path/to/ZendFramework/library/Zend .
  113. # Copy:
  114. % cd library; cp -r path/to/ZendFramework/library/Zend .
  115. ]]></programlisting>
  116. <para>
  117. Nos sistemas Windows, pode ser mais fácil fazer isso do Explorer.
  118. </para>
  119. <para>
  120. Agora que o projeto está criado, os artefatos principais para iniciar o entendimento
  121. são a inicialização da aplicação, configuração, controladores de ação e vizualizações.
  122. </para>
  123. </sect2>
  124. <sect2 id="learning.quickstart.create-project.bootstrap">
  125. <title>A Inicialização da Aplicação</title>
  126. <para>
  127. A classe <classname>Inicialização da Aplicação</classname> define quais recursos e
  128. componentes inicializar. Por padrão, o <link linkend="zend.controller.front">Controlador
  129. Frontal</link> do Zend Framework é inicializado, e ele usa o
  130. <filename>application/controllers/</filename> como diretório padrão o qual procura por
  131. controladores de ação (mais sobre isso mais tarde). A classe parece com o seguinte:
  132. </para>
  133. <programlisting language="php"><![CDATA[
  134. // application/Bootstrap.php
  135. class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
  136. {
  137. }
  138. ]]></programlisting>
  139. <para>
  140. As you can see, not much is necessary to begin with.
  141. Como você pode ver, não é necessário muito para iniciar.
  142. </para>
  143. </sect2>
  144. <sect2 id="learning.quickstart.create-project.configuration">
  145. <title>Configuração</title>
  146. <para>
  147. Enquanto o Zend Framework é em si configuração, muitas vezes você precisa configurar
  148. sua aplicação. A configuração padrão está localizada em
  149. <filename>application/configs/application.ini</filename>, e contém algumas diretrizes
  150. básicas para configurar seu ambiente <acronym>PHP</acronym> (por exemplo, transformar
  151. relatório de erros dentro e fora), indicando o caminho para sua classe inicialização da
  152. aplicação (tão bem como sua classe nome), e o caminho para seus controladores de ação.
  153. Isso parece com o seguinte:
  154. </para>
  155. <programlisting language="ini"><![CDATA[
  156. ; application/configs/application.ini
  157. [production]
  158. phpSettings.display_startup_errors = 0
  159. phpSettings.display_errors = 0
  160. includePaths.library = APPLICATION_PATH "/../library"
  161. bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
  162. bootstrap.class = "Bootstrap"
  163. appnamespace = "Application"
  164. resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
  165. resources.frontController.params.displayExceptions = 0
  166. [staging : production]
  167. [testing : production]
  168. phpSettings.display_startup_errors = 1
  169. phpSettings.display_errors = 1
  170. [development : production]
  171. phpSettings.display_startup_errors = 1
  172. phpSettings.display_errors = 1
  173. ]]></programlisting>
  174. <para>
  175. Diversas coisas sobre este arquivo devem ser notadas. Primeiro, quando usar configuração
  176. de estilo <acronym>INI</acronym>, você pode referenciar constantes diretamente e
  177. expandi-las; <constant>APPLICATION_PATH</constant> é na verdade uma constante.
  178. Adicionalmente note que há várias seções definidas: produção, encenação, teste, e
  179. desenvolvimento. As últimas três herdam configurações do ambiente "produção". Este é um
  180. modo eficiente de organizar configurações para assegurar que as configurações
  181. apropriadas são válidas em cada estágio do desenvolvimento da aplicação.
  182. </para>
  183. </sect2>
  184. <sect2 id="learning.quickstart.create-project.action-controllers">
  185. <title>Action Controllers</title>
  186. <para>
  187. Your application's <emphasis>action controllers</emphasis> contain your application
  188. workflow, and do the work of mapping your requests to the appropriate models and views.
  189. </para>
  190. <para>
  191. An action controller should have one or more methods ending in "Action"; these methods
  192. may then be requested via the web. By default, Zend Framework URLs follow the schema
  193. <constant>/controller/action</constant>, where "controller" maps to the action
  194. controller name (minus the "Controller" suffix) and "action" maps to an action method
  195. (minus the "Action" suffix).
  196. </para>
  197. <para>
  198. Typically, you always need an <classname>IndexController</classname>, which is a
  199. fallback controller and which also serves the home page of the site, and an
  200. <classname>ErrorController</classname>, which is used to indicate things such as
  201. <acronym>HTTP</acronym> 404 errors (controller or action not found) and
  202. <acronym>HTTP</acronym> 500 errors (application errors).
  203. </para>
  204. <para>
  205. The default <classname>IndexController</classname> is as follows:
  206. </para>
  207. <programlisting language="php"><![CDATA[
  208. // application/controllers/IndexController.php
  209. class IndexController extends Zend_Controller_Action
  210. {
  211. public function init()
  212. {
  213. /* Initialize action controller here */
  214. }
  215. public function indexAction()
  216. {
  217. // action body
  218. }
  219. }
  220. ]]></programlisting>
  221. <para>
  222. And the default <classname>ErrorController</classname> is as follows:
  223. </para>
  224. <programlisting language="php"><![CDATA[
  225. // application/controllers/ErrorController.php
  226. class ErrorController extends Zend_Controller_Action
  227. {
  228. public function errorAction()
  229. {
  230. $errors = $this->_getParam('error_handler');
  231. switch ($errors->type) {
  232. case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
  233. case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
  234. case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
  235. // 404 error -- controller or action not found
  236. $this->getResponse()->setHttpResponseCode(404);
  237. $this->view->message = 'Page not found';
  238. break;
  239. default:
  240. // application error
  241. $this->getResponse()->setHttpResponseCode(500);
  242. $this->view->message = 'Application error';
  243. break;
  244. }
  245. $this->view->exception = $errors->exception;
  246. $this->view->request = $errors->request;
  247. }
  248. }
  249. ]]></programlisting>
  250. <para>
  251. You'll note that (1) the <classname>IndexController</classname> contains no real code,
  252. and (2) the <classname>ErrorController</classname> makes reference to a "view" property.
  253. That leads nicely into our next subject.
  254. </para>
  255. </sect2>
  256. <sect2 id="learning.quickstart.create-project.views">
  257. <title>Views</title>
  258. <para>
  259. Views in Zend Framework are written in plain old <acronym>PHP</acronym>. View scripts
  260. are placed in <filename>application/views/scripts/</filename>, where they are further
  261. categorized using the controller names. In our case, we have an
  262. <classname>IndexController</classname> and an <classname>ErrorController</classname>,
  263. and thus we have corresponding <filename>index/</filename> and
  264. <filename>error/</filename> subdirectories within our view scripts directory. Within
  265. these subdirectories, you will then find and create view scripts that correspond to each
  266. controller action exposed; in the default case, we thus have the view scripts
  267. <filename>index/index.phtml</filename> and <filename>error/error.phtml</filename>.
  268. </para>
  269. <para>
  270. View scripts may contain any markup you want, and use the <emphasis>&lt;?php</emphasis>
  271. opening tag and <emphasis>?&gt;</emphasis> closing tag to insert <acronym>PHP</acronym>
  272. directives.
  273. </para>
  274. <para>
  275. The following is what we install by default for the
  276. <filename>index/index.phtml</filename> view script:
  277. </para>
  278. <programlisting language="php"><![CDATA[
  279. <!-- application/views/scripts/index/index.phtml -->
  280. <style>
  281. a:link,
  282. a:visited
  283. {
  284. color: #0398CA;
  285. }
  286. span#zf-name
  287. {
  288. color: #91BE3F;
  289. }
  290. div#welcome
  291. {
  292. color: #FFFFFF;
  293. background-image: url(http://framework.zend.com/images/bkg_header.jpg);
  294. width: 600px;
  295. height: 400px;
  296. border: 2px solid #444444;
  297. overflow: hidden;
  298. text-align: center;
  299. }
  300. div#more-information
  301. {
  302. background-image: url(http://framework.zend.com/images/bkg_body-bottom.gif);
  303. height: 100%;
  304. }
  305. </style>
  306. <div id="welcome">
  307. <h1>Welcome to the <span id="zf-name">Zend Framework!</span><h1 />
  308. <h3>This is your project's main page<h3 />
  309. <div id="more-information">
  310. <p>
  311. <img src="http://framework.zend.com/images/PoweredBy_ZF_4LightBG.png" />
  312. </p>
  313. <p>
  314. Helpful Links: <br />
  315. <a href="http://framework.zend.com/">Zend Framework Website</a> |
  316. <a href="http://framework.zend.com/manual/en/">Zend Framework
  317. Manual</a>
  318. </p>
  319. </div>
  320. </div>
  321. ]]></programlisting>
  322. <para>
  323. The <filename>error/error.phtml</filename> view script is slightly more interesting as
  324. it uses some <acronym>PHP</acronym> conditionals:
  325. </para>
  326. <programlisting language="php"><![CDATA[
  327. <!-- application/views/scripts/error/error.phtml -->
  328. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN";
  329. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd>
  330. <html xmlns="http://www.w3.org/1999/xhtml">
  331. <head>
  332. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  333. <title>Zend Framework Default Application</title>
  334. </head>
  335. <body>
  336. <h1>An error occurred</h1>
  337. <h2><?php echo $this->message ?></h2>
  338. <?php if ('development' == $this->env): ?>
  339. <h3>Exception information:</h3>
  340. <p>
  341. <b>Message:</b> <?php echo $this->exception->getMessage() ?>
  342. </p>
  343. <h3>Stack trace:</h3>
  344. <pre><?php echo $this->exception->getTraceAsString() ?>
  345. </pre>
  346. <h3>Request Parameters:</h3>
  347. <pre><?php echo var_export($this->request->getParams(), 1) ?>
  348. </pre>
  349. <?php endif ?>
  350. </body>
  351. </html>
  352. ]]></programlisting>
  353. </sect2>
  354. <sect2 id="learning.quickstart.create-project.vhost">
  355. <title>Create a virtual host</title>
  356. <para>
  357. For purposes of this quick start, we will assume you are using the <ulink
  358. url="http://httpd.apache.org/">Apache web server</ulink>. Zend Framework works
  359. perfectly well with other web servers -- including Microsoft Internet Information
  360. Server, lighttpd, nginx, and more -- but most developers should be famililar with Apache
  361. at the minimum, and it provides an easy introduction to Zend Framework's directory
  362. structure and rewrite capabilities.
  363. </para>
  364. <para>
  365. To create your vhost, you need to know the location of your
  366. <filename>httpd.conf</filename> file, and potentially where other configuration files
  367. are located. Some common locations:
  368. </para>
  369. <itemizedlist>
  370. <listitem>
  371. <para>
  372. <filename>/etc/httpd/httpd.conf</filename> (Fedora, RHEL, and others)
  373. </para>
  374. </listitem>
  375. <listitem>
  376. <para>
  377. <filename>/etc/apache2/httpd.conf</filename> (Debian, Ubuntu, and others)
  378. </para>
  379. </listitem>
  380. <listitem>
  381. <para>
  382. <filename>/usr/local/zend/etc/httpd.conf</filename> (Zend Server on *nix
  383. machines)
  384. </para>
  385. </listitem>
  386. <listitem>
  387. <para>
  388. <filename>C:\Program Files\Zend\Apache2\conf</filename> (Zend Server on Windows
  389. machines)
  390. </para>
  391. </listitem>
  392. </itemizedlist>
  393. <para>
  394. Within your <filename>httpd.conf</filename> (or <filename>httpd-vhosts.conf</filename>
  395. on some systems), you will need to do two things. First, ensure that the
  396. <varname>NameVirtualHost</varname> is defined; typically, you will set it to a value of
  397. "*:80". Second, define a virtual host:
  398. </para>
  399. <programlisting language="apache"><![CDATA[
  400. <VirtualHost *:80>
  401. ServerName quickstart.local
  402. DocumentRoot /path/to/quickstart/public
  403. SetEnv APPLICATION_ENV "development"
  404. <Directory /path/to/quickstart/public>
  405. DirectoryIndex index.php
  406. AllowOverride All
  407. Order allow,deny
  408. Allow from all
  409. </Directory>
  410. </VirtualHost>
  411. ]]></programlisting>
  412. <para>
  413. There are several things to note. First, note that the <varname>DocumentRoot</varname>
  414. setting specifies the <filename>public</filename> subdirectory of our project; this
  415. means that only files under that directory can ever be served directly by the server.
  416. Second, note the <varname>AllowOverride</varname>, <varname>Order</varname>, and
  417. <varname>Allow</varname> directives; these are to allow us to use
  418. <filename>htacess</filename> files within our project. During development, this is a
  419. good practice, as it prevents the need to constantly restart the web server as you make
  420. changes to your site directives; however, in production, you should likely push the
  421. content of your <filename>htaccess</filename> file into your server configuration and
  422. disable this. Third, note the <varname>SetEnv</varname> directive. What we are doing
  423. here is setting an environment variable for your virtual host; this variable will be
  424. picked up in the <filename>index.php</filename> and used to set the
  425. <constant>APPLICATION_ENV</constant> constant for our Zend Framework application. In
  426. production, you can omit this directive (in which case it will default to the value
  427. "production") or set it explicitly to "production".
  428. </para>
  429. <para>
  430. Finally, you will need to add an entry in your <filename>hosts</filename> file
  431. corresponding to the value you place in your <varname>ServerName</varname> directive. On
  432. *nix-like systems, this is usually <filename>/etc/hosts</filename>; on Windows, you'll
  433. typically find it in <filename>C:\WINDOWS\system32\drivers\etc</filename>. Regardless of
  434. the system, the entry will look like the following:
  435. </para>
  436. <programlisting language="text"><![CDATA[
  437. 127.0.0.1 quickstart.local
  438. ]]></programlisting>
  439. <para>
  440. Start your webserver (or restart it), and you should be ready to go.
  441. </para>
  442. </sect2>
  443. <sect2 id="learning.quickstart.create-project.checkpoint">
  444. <title>Checkpoint</title>
  445. <para>
  446. At this point, you should be able to fire up your initial Zend Framework application.
  447. Point your browser to the server name you configured in the previous section; you should
  448. be able to see a welcome page at this point.
  449. </para>
  450. </sect2>
  451. </sect1>