Zend Framework - quick tutorial (part 2) - directory layout and bootstrapping

August 11th, 2008

part 1 - introduction

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’));

Zend Framework - quick tutorial (part 1) - introduction

August 5th, 2008

I’ve decided to write a quick tutorial about the way I work with Zend Framework. The problems I have, and the way I get through their solution. I think it will be useful for anyone common with the OOP design patterns and PHP programming, who wants to start with Zend Framework.

Introduction

In my practice as programmer I’ve noticed, that almost 90% of the sites we’ve build, have the same problems to solve and similar milestones.

At first why we need a framework? Because most of the programmers start from the beginning with the design of abstraction layers, and the time for the design is absolutely wasted when there are already that kind of abstraction given from almost every framework. Many of them have a big community of programmers around and cover a large scale of programming issues.

The obvious conclusion here is that there are not much sense in loosing that time. In the other part learning and using a framework with the scale of Zend Framework also requires a lot of time, but there’s no need of learning every part of it before you really start. That can happen later on.

That’s what happened in my case. Before two years I’ve designed and build my own framework, which does a lot of good work to organize the working process in the company I worked than. Than I start using a content management systems (CMS), mainly Joomla!, but recently noticed, that our clients don’t need that many functionality as Joomla! offers. They did not create a “menu” or add “template”.

With the idea to create web systems with my own CMS I decided to use Zend Framework. Not just like that, but mostely because the other PHP frameworks like CakePHP or Symfony looked to me more like CMS, something that I don’t want, because I’d like to build my own steping on the base of framework which gives those abstraction layers like db connection, acl etc.

With this tutorial I’ll describe the path I passed trough using the Zend Framework, and how it can be basicaly used.

part 2 - directory layout and bootstrapping

How to remove onPress dotted outline of html links?

August 5th, 2008

One of the questions I’ve always like to answer is how to remove a default link decoration “onPress” event. Almost every browser puts a dotted outline around the link.

At last today I get how to remove this feature described in the following article.

Why should we learn a framework?

August 4th, 2008

If anybody still asks should we learn a framework, I recommend him to read the recent post
of Ian P. Christian.

Before you start, however there are no recommendation there about which framework you’ve to choose, but he gives a good examples and advices why there’s no need to apply common design patters over and over again.

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

July 31st, 2008

Всеки, който започва да използва нов 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.

Zend_Controller_Front plugins

July 31st, 2008

Една от особеностите на Zend Framework Front Controller е фактът, че може лесно да се напишат и ползват plugins към него. Колкото до официалната документация на ZF, поне според мен, не е достатъчно описателна и не дава ясна представа какво точно правят тези plugins и колкото и добре да е показано как се пишат и как са замислени не става известно какво предимство дават на приложението.

Добра статия за това как да се напише plugin и какви предимства дава може да се намери в една статия, която намерих днес.

Ето и някои от предимствата на плъгините:

  1. Инициализация на приложението
  2. Кеширане
  3. Инициализация на router-а
  4. Authentication и Authorization
  5. Филтриране на изходния XHTML

Как се започва със Zend Framework

July 31st, 2008

Тъй като има достатъчно много статии как точно може да се започне със Zend Framework, днес открих една много интересна статия, която съдържа един много интересен .pdf описващ началото на един Zend Framework проект. Ако някой има нужда да го разгледа всичко е свободно за използване.

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

Treality Web Site

March 10th, 2008

Official web site of the company I’m working for. Treality.com is still beta but online. Take a look!Home

Perl Regular Expressions

October 17th, 2007

For everyone who did write a code someday comes the question of using regular expressions. Almost everybody has heart about automatic and regular languages. Assume you have all word for a given languages, which means all possible combination between the letters of a given alphabet. For all these possible word only few construct the “language” as we know this term. Of course there’s also need of grammatic, etc. But however we have the set of words in a given language.

Than comes the task to find those of the words of the language that match a given condition. In fact the regular expressions are a powerful tool to do this job.

Using PHP you can use preg_ functions, which will perform a perl regular expressions match. In my case I had to find in about 180 .html files specific words.

Assume the files contain something like:

<!-- wellformed html comment -->
<tr>
<td class="classname1"><img ...></td>

<td class="classname2">

<a ... >

Word to match

</a>

</td>

</tr>

<tr>

<td ...></td>

<td ...></td>

</tr>

<!--wellformed html comment-->

The regular expressions for preg_replace function I used was something like this:

'/^[t|s]*<tr>.*?$n^.*?<td.*?</td>.*?$n.*?
<td.*?$n.*?<a.*?>.*?$n.*?Word  to  match.*?$n.*?</a>.*$n.*?</td>.*$n.*?
</tr>.*$n.*?<tr.*$n.*?<td.*$n.*?<td.*$n.*?</tr>/m'

… and it worked for me. In fact if you use ’s’ instead of ‘m’ modifier that’s gonna be you mistake cause of the multiple matches before the current tag you want to match.

amarok plays mp3

September 20th, 2007

I’m on Fedora 7. Due to lack of free time I just saw the Amarok is not playing mp3 files and solved the problem simply by installing the XMMS. Today, realizing that I’m using Konqueror all the day long and almost everything related to the file system, browsing etc. is performed by Konqueror, I decided to configure lastly my Amarok.

And as it appears I had good luck. I found this lovely article which I recommend to everyone who’s gonna configure his own player.