Category Archives: featured

Zend Framework – quick tutorial (part 2)

Directory Layout and Bootstrapping.

When someone starts with the learning of a framework, first he begins to read various articles to understand the basic rules to work with.

There are a lot of tutorials how exactly to start, and there is also an official quick start guide, but beside this there are too much advices how should you directory layout look like.

For me the following directory layout is working well. I don’t remember exactly where I’ve found it, but I think many people use it.

  • application
    • admin
    • controllers
    • models
    • views
  • content
    • controllers
    • models
    • views
  • layouts
  • bootstrap.php
  • config.ini
  • library
  • Zend
  • public
  • index.php

Almost half of the sources “how to start” recommend all of the initialization should be in index.php in the public folder. In fact all the logic of the public/private folders is that we don’t like to show anything on the web, and that’s why index.php contains only the following peace of code (it’s recommended to leave the file open from the ?> closing tag):
<?php
require '../application/bootstrap.php';

Anything else, all the initialization is in bootstrap.php:

error_reporting (E_ALL | E_STRICT);

ini_set (‘display_startup_errors’, 1);
ini_set (‘display_errors’, 1);

set_include_path (‘../library’ . PATH_SEPARATOR . get_include_path());

require_once “Zend/Loader.php”;
Zend_Loader::registerAutoload();

$front = Zend_Controller_Front::getInstance();

$front->throwExceptions(true);

$front->setControllerDirectory(array(‘default’ => ‘../application/content/controllers’,
‘admin’   => ‘../application/admin/controllers’));

$front->dispatch();
We set the error reporting to be ON, which si good when you develop any application and to collect all error messages. Than add the library folder in the include path with that line of code:

set_include_path(‘../library’ . PATH_SEPARATOR . get_include_path());

Next step is to start the __autoload functionality built in Zend Framework:

require_once “Zend/Loader.php”;
Zend_Loader::registerAutoload();

Finally start the front controller which implements the singleton pattern and point to the two main directories – admin and content. I used them for administration panel and front end, but you can used as many as you application needs:
$front->setControllerDirectory(array('default' => '../application/content/controllers',
'admin'   => '../application/admin/controllers'));

Related Links

Zend_Db tutorial

Zend_Layout

Или как да не пишем във всеки шаблон, че ще има header.

Всеки, който започва да използва нов web framework първоначално се запитва за няколко основни неща. Като цяло те и отговарят на MVC практиката.

  1. Как да направим така че всичките ни състояния в сайта да бъдат описани в различни файлове, така че да можем лесно да си намираме и поддържаме кода.
  2. Как да се погрижим за правата и ролите на различните потребители на сайта.
  3. Как да разделим html-а на няколко файла, за да не пишем по един милион пъти includes на header или footer.

Почти всеки, който се е сблъсквал с PHP програмиране е чувал за Smarty и когато някой, по-често псевдо разбирач, ти изреди една плеяда колко е ретроградно да се слага php код измежду html таговете и как трябвало Smarty да се притече на помощ, ето един добър довод за излагане против Smarty.

Хубаво е да се ползва Smarty. Няма проблем. Само че нека си представим следния пример. Имаме сайт с header – content – footer. Като обикновено header-a съдържа разни връзки към css и meta тагове. Със Smarty като искаме да използваме тая структура за 10 файла, 10 пъти ще имаме следния код:

{include file=”header.tpl”}

{include file=”content.tpl”}

{include file=”footer.tpl”}

и ако това се повтаря в 100 файла, ще се наложи, няма как – 100 пъти едно и също за тоя header и footer.

След като и Zend Framework се е измъчил в по-предишни версии, доколкото разбирам, все пак аз отскоро се захванах с него и направо започнах от 1.5.3, сега проблемът се решава от Zend_Layout. A и сблъсквайки се с проблема с header-a и footer-a стигнаь до четене на няколко урока, от които разбрах, че хората преди са се опитвали да решат проблема с plugin към Front Controller-а и явно това е било разпространената практика.

Може би и на създателите на ZF им е станало ясно, че така няма да стане и затова се е погрижил Zend_Layout.

Дори сега се появяват уроци които се стремят да помогнат на решаването на този проблем с помощта на plugin, но аз препоръчвам да не се захваща никой с тях, въпреки че може на някой да му е интересно. Най-добре да се насочи към използването на Zend_Layout. За жалост пък при него поне официалната документация ми се видя недостатъчно, но пък намерих една презентация от webinar на Zend.