getting-started-with-the-zend-framework_122.pdf
(
83 KB
)
Pobierz
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
Getting Started with the Zend Framework
By Rob Allen,
www.akrabat.com
Document Revision 1.2.2
Copyright © 2006
This tutorial is intended to give a very basic introduction to using the Zend Framework to write
a basic database driven application.
NOTE:
This tutorial is intended for version 0.6 of the Zend Framework and stands a very
chance of not working with the latest development code in Subversion or any other released
version!
Model-View-Controller Architecture
The traditional way to build a PHP application is to do something like the following:
<?php
include "common-libs.php";
include "config.php";
mysql_connect($hostname, $username, $password);
mysql_select_db($database);
?>
<?php include "header.php"; ?>
<h1>Home Page</h1>
<?php
$sql = "SELECT * FROM news";
$result = mysql_query($sql);
?>
<table>
<?php
while ($row = mysql_fetch_assoc($result)) {
?>
<tr>
<td><?php echo $row['date_created']; ?></td>
<td><?php echo $row['title']; ?></td>
</tr>
<?php
}
?>
</table>
<?php include "footer.php"; ?>
Over the lifetime of an application this type of application becomes un-maintainable as the
client keeps requesting changes which are hacked into the code-base in various places.
One method of improving the maintainability of the application is to separate out the code on
the page into three distinct parts (and usually separate files):
Model
The model part of the application is the part that is concerned with the
specifics of the data to be displayed. In the above example code it is the
concept of “news”. Thus the model is generally concerned about the
“business” logic part of the application and tends to load and save to
databases.
View
The view consists of bits of the application that are concerned with the
display to the user. Usually, this is the HTML.
Controller
The controller ties together the specifics of the model and the view to
ensure that the correct data is displayed on the page.
Page 1 of 19
The Zend Framework uses the Model-View-Controller (MVC) architecture. This is used to
separate out the different parts of your application to make development and maintenance
easier.
Requirements
The Zend Framework has the following requirements:
·
PHP 5.1.4 (or higher)
·
A web server supporting mod_rewrite functionality. This tutorial assumes Apache.
Getting the Framework
The Zend Framework can be downloaded from
http://framework.zend.com/download
in either
.zip or .tar.gz format. At the time of writing, version 0.6 is the current version. You must
download version 0.6 for this tutorial to work.
Directory Structure
Whilst the Zend Framework doesn’t mandate a directory structure, the manual recommends a
common directory structure. This structure assumes that you have complete control over your
Apache configuration, however we want to make life a little easier, so will use a modification.
Start by creating a directory in the web server’s root directory called
zf-tutorial
. This
means that the URL to get to the application will be
http://localhost/zf-tutorial
.
Create the following subdirectories to hold the application’s files:
zf-tutorial/
/application
/controllers
/models
/views
/library
/public
/images
/scripts
/styles
As you can see, we have separate directories for the model, view and controller files of our
application. Supporting images, scripts and CSS files are stored in separate folders under the
public directory. The downloaded Zend Framework files will be placed in the library folder. If
we need to use any other libraries, they can also be placed here.
Extract the downloaded archive file, ZendFramework-0.6.zip in my case, to a temporary
directory. All the files in the archive are placed into a subdirectory called
ZendFramework-
0.6
. Copy the contents of
ZendFramework-0.6/library
into
zf-tutorial/library
.
Your
zf-tutorial/library
should now contain a sub-directory called
Zend
and a file
called
Zend.php
.
Bootstrapping
The Zend Framework’s controller, Zend_Controller is designed to support websites with clean
urls. To achieve this, all requests need to go through a single index.php file, known as the
bootstrapper. This provides us with a central point for all pages of the application and ensures
that the environment is set up correctly for running the application. We achieve this using an
.htaccess file in the
zf-tutorial
root directory:
Page 2 of 19
zf-tutorial/.htaccess
RewriteEngine on
RewriteRule .* index.php
php_flag magic_quotes_gpc off
php_flag register_globals off
The RewriteRule is very simple and can be interpreted as “for any url, redirect to index.php”.
We also set a couple of PHP ini settings for security and sanity. These should already be set
correctly, but we want to make sure! Note that the php_flag settings in .htaccess only work if
you are using mod_php. If you use CGI/FastCGI, then you need the make sure that your
php.ini is correct.
However, requests for images, JavaScript files and CSS files should not be redirected to our
bootstrapper. By keeping all these files within the
public
subdirectory, we can easily
configure Apache to serve these files directly with another .htaccess file in
zf-tutorial/public
:
zf-tutorial/public/.htaccess
RewriteEngine off
Whilst not strictly necessary with out current rewrite rules, we can add a couple more
.htaccess files to ensure that our application and library directories are protected:
zf-tutorial/application/.htaccess
deny from all
zf-tutorial/library/.htaccess
deny from all
Note that for .htaccess files be used by Apache, the configuration directive AllowOverride
must be set to All within your httpd.conf file. The idea presented here of using multiple
.htaccess files is from Jayson Minard’s article “
Blueprint for PHP Applications: Bootstrapping
(Part 2)
”. I recommend reading the entire series of articles.
The Bootstrap File: index.php
zf-tutorial/index.php
is our bootstrap file and we will start with the following code:
zf-tutorial/index.php
<?php
error_reporting(E_ALL|E_STRICT);
date_default_timezone_set('Europe/London');
set_include_path('.' . PATH_SEPARATOR . './library'
. PATH_SEPARATOR . './application/models/'
. PATH_SEPARATOR . get_include_path());
include "Zend.php";
Zend::loadClass('Zend_Controller_Front');
// setup controller
$baseUrl = substr($_SERVER['PHP_SELF'], 0,
strpos($_SERVER['PHP_SELF'], '/index.php'));
$frontController = Zend_Controller_Front::getInstance();
$frontController->setBaseUrl($baseUrl);
$frontController->setControllerDirectory('./application/controllers');
$frontController->throwExceptions(true);
// run!
$frontController->dispatch();
Page 3 of 19
Note that we do not put in the
?>
at the end of the file as it is not needed and leaving it out
can prevent some hard-to-debug errors if additional whitespace occurs after the
?>
.
Let’s go through this file.
error_reporting(E_ALL|E_STRICT);
date_default_timezone_set('Europe/London');
These lines ensure that we will see any errors that we make (assuming you have the php.ini
setting
display_errors
set to on). We also set up our current time zone as required by
PHP 5.1+. Obviously, you should choose your own time zone.
set_include_path('.' . PATH_SEPARATOR . './library'
. PATH_SEPARATOR . './application/models/'
. PATH_SEPARATOR . get_include_path());
include "Zend.php";
The Zend Framework is designed such that its files must be on the include path. We also
place our models directory on the include path so that we can easily load our model classes
later. To kick off we have to include the files
Zend.php
to gives us access to the
Zend
class
which has the required static functions to enable us to load any other Zend Framework class
Zend::loadClass('Zend_Controller_Front');
Zend::loadClass loads the named class. This is achieved by converting the underscores in
the class name to path separators and then adding .php to the end. Thus the class
Zend_Controller_Front
will be loaded from the file Zend/Controller/Front.php. If you
follow the same naming convention for your own library classes, then you can utilise
Zend::loadClass()
to load them too. We need to load the front controller class and the
router class.
The front controller uses a “router” class to map the requested URL to the correct PHP
function to be used for displaying the page. In order for the router to operate, it needs to work
out which part of the URL is the path to our
index.php
so that it can look at the url elements
after that point. In principle, the request object (an instance of
Zend_Controller_Request_Http
) should be able to auto-detect the correct base URL. In
practice, I’ve found that it doesn’t work with my particular installation, at least. Fortunately, we
can set the base URL ourselves using the function
setBaseUrl()
. This function is available
within the http request class and also within the front controller so that we don’t have to worry
about instantiating our own request object.
We now set the base URL for the router to the correct URI to our index.php. I’ve used
$_SERVER['PHP_SELF']
to work it out, so it should work for most server configurations. If it
doesn’t work for you, then change the assignment to
$baseUrl
to the correct URL to
index.php
for your system.
// setup controller
$baseUrl = substr($_SERVER['PHP_SELF'], 0,
strpos($_SERVER['PHP_SELF'], '/index.php'));
$frontController = Zend_Controller_Front::getInstance();
$frontController->setBaseUrl($baseUrl);
We also need to configure the front controller so that it knows which directory our controllers
are in.
$frontController->setControllerDirectory('./application/controllers');
As this is a tutorial and we are running on a test system, I’ve decided to instruct the front
controller to throw all exceptions that occur. By default, the front controller will catch them for
us and store them in the _
exceptions
property of the “Response” object that it creates. The
response object holds all information about the response to the requested URL. This includes
Page 4 of 19
header, page content and exceptions. The front controller will automatically send the headers
and display the page content just before it completes its work
This can be quite confusing for people new to the Zend Framework, so it is easier to just re-
throw so that the exceptions are easily visible. Of course, on a production server, you
shouldn’t be displaying errors to the user anyway!
$frontController->throwExceptions(true);
Finally we get to the heart of the matter and we run our application:
// run!
$frontController->dispatch();
If you go to http://localhost/zf_tutorial/ to test, you should fatal error similar to:
Fatal error
: Uncaught exception 'Zend_Exception' with message 'File
"./application/controllers\IndexController.php" was not found.
(etc.)
This is telling us that we haven’t set up our application yet. Before we can do so, we had
better discuss what we are going to build, so let’s do that next.
The Website
We are going to build a very simple inventory system to display our CD collection. The main
page will list our collection and allow us to add, edit and delete CDs. We are going to store
our list in a database with a schema like this:
Fieldname
Type
Null?
Notes
id
Integer
No
Primary key, Autoincrement
artist
Varchar(100)
No
title
Varchar(100)
No
Required Pages
The following pages will be required.
Home page
This will display the list of albums and provide links to edit and delete
them. Also, a link to enable adding new albums will be provided.
Add New Album
This page will provide a form for adding a new album
Edit Album
This page will provide a form for editing an album
Delete Album
This page will confirm that we want to delete an album and then
delete it.
Organising the Pages
Before we set up our files, it’s important to understand how the framework expects the pages
to be organised. Each page of the application is known as an “action” and actions are
grouped into “controllers”. E.g. for a url of the format
http://localhost/zf-
tutorial/news/view
, the controller is
news
and the action is
view
. This is to allow for
grouping of related actions. For instance, a
news
controller might have actions of
current
,
archived
and
view
.
The Zend Framework’s controller reserves a special action called
index
as a default action.
That is, for a url such as
http://localhost/zf-tutorial/news/
the
index
action
within the news controller will be executed. The Zend Framework’s controller also reserves a
default controller name should none be supplied. It should come as no surprise that this is
Page 5 of 19
Plik z chomika:
Retran
Inne pliki z tego folderu:
Zend Framework Tutorial - Samouczek _ Heavymind.pdf
(883 KB)
Zend_framework+smarty.doc
(76 KB)
getting-started-with-the-zend-framework_122.pdf
(83 KB)
PHP 4. Biblia.pdf
(19996 KB)
Flash.i.PHP.Podstawy.rar
(4022 KB)
Inne foldery tego chomika:
Heroes 3 Hd Edition
JaggedAlliance2PL
peugeot citroen
PHP i MySQL. Tworzenie stron WWW. Vademecum profesjonalisty
POZYCJONOWANIE
Zgłoś jeśli
naruszono regulamin