Zendframework Getting Started Tutorial

Source: Internet
Author: User
Tags download zend what is lamp zend framework

I. Introduction of the ZEND Framework 1. What is Zendframework

The Zend framework (ZF or ZFW) is a PHP development framework technology developed by PHP's parent company Zend, which provides an excellent, simple, comprehensive development environment and offers a number of available solutions that can be used to build a stable, upgradable Web application.

The so-called framework, which is a reusable design of the whole or part of the system, first provides a reusable application Reference Architecture that clarifies the entire design, dependencies between components, responsibility allocation and control processes, including design specifications, and so on. It provides a solution to some common problems.

In addition, the Zend Framework uses a common MVC model (which is described later), which makes it easier to achieve the purpose of separation of concerns, which makes it easier to build a Web application based on the MVC architecture (typical MVC Web schemas and structs, and so on, which are similar in principle) ( There are many similar frameworks for PHP such as: YAF)

Zend's official website: http://www.zend.com/en/

2. What is lamp

Lamp is a linux+apache+mysql+perl/php/python abbreviation, they are often used to build dynamic Web site or server open source software, itself is a separate program, but because it is often used together, has a higher degree of compatibility, Together make up a powerful Web application platform, because are open-source software, in addition to the temptation of free use, there is the ability to modify the source code, self-control and other advantages, lamp is most web developers and many large companies (such as Facebook and Baidu) the choice. From the traffic on the site, more than 70% of the traffic is lamp to provide, visible lamp is the most powerful website solutions. (Other similar scenarios such as MS's. NET Framework and Oracle's Java EE framework are equally powerful)

Why do you say lamp, because the combination of these software is strong enough to mention one must mention the other three of the point, and in the construction of the laboratory site, we use PHP, we take the framework of the lamp of course

3. Installation of the Zend framework Xampp:apache Friends

When it comes to installation, lamp installation is very cumbersome, because these software are independent software, and open source software is characterized by the installation needs to be modified configuration files, the software is interdependent, so the configuration is cumbersome, often problems, Of course, if you want to understand lamp and later optimization and personalized configuration, it is necessary to understand the configuration of each software, but if at the beginning of the encounter a lot of difficulties will always affect everyone's enthusiasm, and Xampp's appearance solved the problem. XAMPP is an integrated release version of the easy-to-install lamp framework that contains MySQL, PHP, Perl, Apache, Web site http://www.apachefriends.org/zh_cn/xampp.html, which supports Linux , Windows and Mac platforms, the installation is very simple, and normal software, as long as the download, run the software.

After the installation is complete, you can start the XAMPP Control Panel to see how the above software works, and you can also enter http://localhost in the browser to manage XAMPP's integrated software. (General Apache bound to 80 port, you can modify, modify the words to use: xx method to access.)

Zend Installation and use

Zendframework installation only needs to go to the Zend Framework's official website http://framework.zend.com/download download Zend Framework of the program installation package extracted to a specified directory, Then php.ini (PHP configuration file) in the include_path to add the Zend directory can be extracted.

It is also important to note that the default Zend framework uses the MVC mechanism, which uses rewrite to jump, which requires that the option to allow rewrite be modified in the Apache configuration file (typically httpd.conf), the steps required are:

1. Find LoadModule rewrite_modulemodules/mod_rewrite.so to remove the # from the front

2. In the directory where the project is located <directory "ProjectPath" > Modify the value of allowoverride to All,order Allow,deny/allow from all

3. Create the. htaccess file at the root of the project with the content

Rewriteengine on #重写引擎打开

Rewriterule!\. (JS|ICO|GIF|JPG|PNG|CSS) $ index.php

#制定除js, files other than ico,gif,jpg,png,css are reset to index.php,index.php for the first page of the project (actually the front-end forwarding control page)

Simple Zend Framework Installation test method:

To create a file test.php content:

<?php

Require_once (' zend/date.php ');

$date =new zend_date ();

Echo $date

?>

If the output can be normal, the Zend installation is generally normal.

Also, if you want to use <?=someVariable?> instead of <?php Echo $value?> in the view file, you need to open short opentag in php.ini, Short_open_tag = On only, otherwise the <?=?> expression cannot be parsed properly.

Second, the MVC Framework 1. What is the MVC framework

MVC (Model-view-controller) is a design pattern that integrates many design patterns, forcing the input, processing, and output of a program to be separated into three core components: Model, View and controller, where

Model: Responsible for data processing, including business logic.

View: Responsible for the presentation of the data and get input.

Controller: Responsible for receiving input from view and manipulating model to complete user requirements, then call view to return data to the user.

2. Typical examples of MVC frameworks

Here are two examples of MVC, one in the traditional desktop program, and the other with the Zend framework as an example, detailing Zendframework mvc.

2.1 Traditional Desktop programs: Text editor

Text editor Everyone should have used, here use a in the "Simple to use MFC" in the example of Mr. Houtie, the function to be implemented does not need to repeat, there is a text box is responsible for the display of text, the user can modify the text.

of which:

Model, which is responsible for invoking the operating system underlying file Operations API, completes the function has

A) Read the contents of the file

b) Modify the contents of the file: including editing and deleting content

c) Create files, delete files,

View, is responsible for displaying the contents of the current file to the user, and is responsible for providing UI interface, to manipulate the text, the completion of the functions are:

A) display the current contents of the text

b) Get the user's possible input: text selection, text copy, text pasting, text editing, file opening, deletion and new, etc.

Controller, responsible for responding to user requests from the view layer, invoking the corresponding model operation to perform the user's needs, the completed functions are:

A) respond to the view request and convert it to the corresponding model method call

b) When the operation is completed, returns the returned results to the specified view, showing the results to the user

(Note: In the function of the text editor, there is a case, there are multiple text windows, display the contents of the file, when there are multiple windows to work on a file at the same time, so that there is a common resource modification problem, and in a text window modified text, other text editor should also display the modified values, This requires that each text window has a real-time understanding of the file's status, how can it be implemented? Use observer mode.)

3. The MVC framework in Zend

Here, we will briefly introduce the MVC components of the Zend Framework and give a simple implementation of a Zend Framework program. ZENDFRAMEWORKD's MVC framework is similar to the traditional MVC framework, but it's a little different because it's used in the Internet environment.

Because of the MVC framework, we need to give a specification of the project's directory structure, the typical directory structure is as follows

app/

----controllers/

----models/

----views/

----------scripts/

Where the app is a subdirectory under the root directory, save the MVC code, save all the controllers,models directories in controllers, save all models code, and save all the view code in views/scripts.

3.1 Zend_controller

Zend_controller is the controller part of the Zend framework, where the Zend_controller_front class implements the front-end controller design pattern,

3.1.1 Front Controller

Front-End controller design mode: Since all requests from the Internet environment have httpurl requests from the browser to the server, the input of the Web application is the request for the server, in order to implement the mapping from the request to the controller, We send all requests first to the front-end controller front controllers, configured by the front-end controller, selecting the appropriate controller for the distribution (dispatch) request, and then processing the requested response by the specific controller. (Front-end controller design patterns are common in web programs, and structs is also used in this mode)

The general front-end controller is defined in the Portal file index.php (the root directory), and the Declaration code is:

Initializing an Frontcontroller instance

$front =zend_controller_front::getinstance ();

Ability to throw exceptions during distribution, which is then placed in the desired object after the default exception is caused

$front->throwexceptions (TRUE);

Set the default processing controller name

$front->setdefaultcontrollername (' home ');

Setting the Controllers Directory

$front->setcontrollerdirectory ($dir. ' \app\controllers ');

When all configurations are complete, the front-end controller needs to be responsible for the request forwarding of the entire program (like the main program in the WIN32 program) and processing the distribution request:

try {

Start running

$front->dispatch ();

} catch (Exception $e) {

Handling Exceptions

echo $e;//include_once ' exception.php ';

}

Frontcontroller's dispatch method can implement the controller routing, distribution, response, etc., the distribution process consists of three different events:

² Routing (Routing), using router router, executes only once and takes advantage of the value in the request object when calling the dispatch () method.

² distribution (dispatching), using the dispatcher dispatcher, occurs in the loop

² response (Response), the front controller returns the response object after processing is complete

3.1.2 Action Controller

Zend_controller: Each specific controller should be inherited from the class Zend_controller_action, is an action controller class, this class has the most basic class Controller method, To handle the operation between the associated view and model, each specific controller should inherit from this class.

Action controller: The Publicfunction xxxaction () method in each controller is a control action that defines the actions that the Controller should take when confronted with different requests. For example , when requesting http://localhost/home/index this URL, the request will be forwarded to the home controller's indexaction action, The indexaction defines how to handle this request.

L manipulate Request\response objects, get parameters:

In the Action Controller function (xxxaction), some common data can be accessed through the API, such as:

²request object: Obtained by Getrequest (), returns a Zend_controller_request_abstract instance

²response object: Obtained by GetResponse (), returns a Zend_controller_response_abstract instance that can be modified by methods on this object to modify the Response object

²request Parameters: Parameters passed by post or get can be obtained using the _getparam ($key) method or _getallparams (), or the request parameter can be set by the _setparam method (typically used to forward requests to other actions )

L Operation View:

² views are represented by the Zend_view object, and in Zend_controll_action, the corresponding Zend_view object can be initialized by the Initview () or the render () method, by default assuming that the view exists views/scripts/ subdirectory, the base directory is views/scripts/when the view script is specified

(typically using Initview in the Init method of zend_controller_action, using render in other xxxaction)

²render () is used to parse the view, declared as render (string$action=null,string $name =null,bool $noController =false), and if no arguments are passed, the default parsing script is in views/ Scripts/[controller name]/[action]. $viewSuffix value

² Note: The Controller and action names contain "_", ".", "-" words, these separators will be formatted as "-"

L Steering Method:

²_forward ($action ...) Method for performing another action

²_redirect ($url ...) Method for redirecting to another place

3.1.3 Action Helper

The Action Helper (zend_controller_action_helper) can add functionality to the Zend_controller_action class's action controller (runtimeand/or On-demand functionality).

Helper brokers exist in the $_helper member of the Zend_controller_action class to get and invoke the helper. is an object of the Zend_controller_action_helperbroker class that supports the Addhelper method to add an assistant to the broker (you can also join with Addprefix and Addpath methods). Equivalent to an action's assistant butler.

Built-in Action helper

L Flashmessenger: Allows the user to pass messages that may need to be seen in the next request, using Zend_session_namespace to store the message (for internal message delivery)

L Redirector: Redirector, can help program redirect to new URL

L Viewrenderer: View Rendering helper, can help us not to create a view instance in the controller, the view object is automatically registered with the controller, you can automatically set the view script, assistant, filter path according to the current module, Assigning the current module name to the prefix of the class name of the helper and filter, can automatically render the view script, we can not write Initview and render.

Use method,

View Render Helper

$view =new Zend_view (Array (' encoding ' = ' UTF-8 '));

Create a view render

$view _render=new Zend_controller_action_helper_viewrenderer ($view);

Set the suffix of the view script, which is used here. php

$view _render->setviewsuffix (' php ');

Add view Renderhelper to the action Assistant so that we can automatically render a view script with the suffix. php with the render helper, and the rules for rendering are consistent with the default Initview.

Zend_controller_action_helperbroker::addhelper ($view _render);

3.2 Zend_view

How to use Zend_view: Create a Zend_view instance in the controller (also can be created by the View Render helper, we don't have to write it ourselves). Then assign the variable you want in the view to it, and then render the view using render.

The General code is:

<?php

$view =newzend_view ()

$view->a= '

$view->c= "//or assign () with view to support associative array assignment

Echo$view->render (' someview.php ')

?>

The way we use HTML in the view script is mixed with PHP, the variable to be used is passed to it by the controller, $this->view->xxx; is accessed using the $this->xxx method in the script.

3.3 Zend_model

In the model section is generally complete access to data, management and implementation of business logic, the general model of the storage directory in and controllers root directory of the models folder, model is generally between the PHP class can be. In general, we have data in the building of Web applications exist in the database, here is a brief discussion of the Zend in the database support it.

The zend_db component is a database Support section in the Zend framework, and is composed of Zend_db_adapter, Zend_db_statement, Zend_db_profiler, Zend_db_select, zend_db_ Table, Zend_db_table_row and Zend_db_table_rowset, etc.

Zend_db_adapter is the database Abstraction Layer API for the Zend framework, which is based on PDO and can support multiple databases. The adapter is configured in the form

Connect to MySQL Database

$db =zend_db::factory (' Pdo_mysql ', $config);

The $config stores configuration information for the connection database, such as address, port, user name, password, database name used, and so on. After the connection, you can query the database directly using the $db->query () method.

Supported Operations for Zend_db_adapter:

L Query ($sql, $bind =array ()), querying the database, $bind the number to be bound

L Queryinto ($text, $value, $type =null) for the harmless handling of SQL

Insert ($table, array $bind), inserts the data, $table to indicate that the $bind is the field of the table and the binding array directly to the inserted data.

L Lastinserid ($tableName =null, $primaryKey =null), returns the ID of the data just inserted

L Fetchrow ($sql, $bind =array ()), used to query the return results of SQL, and the returned results can be traversed in the form of foreach ($resultas $key = = $value).

L Delete ($table, $where = ") deletes the table $table record in the database

L Update ($table, array $bind, $where = ") is used to change the contents of $bind array-related key values on the table $table based on $where constraints.

By the above zend_db_adapter can be in general to complete the operation of the database, our laboratory site is also basically used zend_db_adapter related content, while the other zend_db control provides a variety of more powerful functions, we can explore their own, I won't repeat it here.

Three, Zend Common control

It says so much about MVC, the following is a description of some simple component usages of the Zend framework by giving specific examples of the zendframework used during the login process.

1. From the Login

A simple login process we all understand, first we need to give a user name password form, and then after the user entered the user name password, click Submit Submit, our program compares the user input with the data in the background database to see if authentication is passed, Verify that you save a session for user access, otherwise prompt the user name password input error, re-enter. Complex login controls also include verification codes and so on, which we don't discuss here.

Note: There are a lot of things to talk about login, such as Single Sign-on what is it? You can check it out for yourself.

The Init method and login action for the login control controller are given below: The relevant content is followed by:

The requested URL should resemble the following: Http://localhost/member/login; indicates that the form is referred to membercontroller for processing in the loginaction.

The initialization function init of the controller is given first, which is typically initialized with various properties

function init ()

{

Get the database interface, stored in the object registry Zend_registry in advance

$this->db=zend_registry::get (' database ');

Set the action and Controller properties of a view

$this->view->action= $this->_getparam (' action ');

$this->view->controller= $this->_getparam (' controller ');

Default-loaded JS for easy use in view

$this->view->javascript=array (' jquery.inline.js ', ' paper.js ');

Get logged in state, state stored in zend_session

$session =new zend_session_namespace ();

$login = $session->login;

if (Isset ($login)) {

Assigning values to related variables in view

$this->view->aid= $login [' Aid '];

$this->view->priv= $login [' Priv '];

$this->view->name= $login [' name '];

}

else {

$this->view->aid= $this->view->priv= $this->view->name=0;

}

Default title

$this->view->title= ' web homepage ';

}

Then give the login action handler

function Loginaction ()

{

$url = '/home/index ';

Get the user name and password entered by the user from the request parameter

$user = $this->_getparam (' user ');

$pass =md5 ($this->_getparam (' Pass '));

Start session

$session =new zend_session_namespace ();

try{

$ACC =member::login ($this->db, $user, $pass); Call the model query to specify whether there are entries in the table that are $user and $pass satisfied

if (Is_array ($ACC)) {

$ACC is an array that shows the entries that meet the criteria, validates the success, and then puts the resulting information into the $session to make it easier for other modules to use

$session->login= Array

(' aid ' = $ACC [' Aid '],

' Name ' = $ACC [' name '],

' Priv ' = $ACC [' Priv '],

' User ' = $ACC [' user '];

}

catch (Zend_exception $e) {

}

Rendering using the home/index.php page

$this->renderscript (' home/index.php ');

}

2. Zend_session

After the login process is successful, we inevitably need to save the user's session information, and this session information is implemented by the control zend_session in the Zend Framework. (that is, the contents of $_session in PHP are managed by zend_session)

We know that in PHP to use the session first to open the session, and we use the Zend_session::newzend Session_namespace () method will default on the Zend_session::start () method, and set Zend_session::setoptions (Array (' strict ' =>true)); You can block the call to the Zend_session::start () method at New Zend_session_namespace ().

(We usually open zend_session::start () before we use the Session;)

So we use the zend_session of the general use of the following two kinds:

L zend_session::setoptions (Array (' strict ' =>true));

Zend_session::start ();

$mySpace =newzend_session_namespace (' mySpace ');

L or use directly when needed

$mySpace =newzend_session_namespace (' mySpace ');

The second way in the example above (in fact, the above $myspace is actually saved in $_session[' MySpace ').

3. Zend_registry

Register is an object registry that can store any object in the object's registry so that it can be called anywhere and anytime, and can be said to be a global variable manager.

can be used

$reg =zend_registry::getinstance ();

$reg->set (' database ', $db);

To obtain a default Zend_registry registry variable (the database object in this case) and call the set ($key, $value) method on it to set the value of the global variable, which can then be passed anywhere through zend_registry::isregistered ( $key) to check if an object exists, you can use Zend_registry::get ($key) to get the contents of the object in the default registry, and you can delete the contents of the object's registry by Zend_registry::_unsetinstance ($key).

The difference between Zend_registry and zend_session (translated from online):

The main difference between Zend_registry and Zend_session is that at their scope, the scope of the zend_registry is valid for the current request, which is the Zend_ Register data cannot be shared by different pages, but if we define Zend_register data in index.php (front-end forwarding-controlled pages), it can be used in all controllers/actions zend_ Register because they have just been redirected to index.php before they are uploaded to these specific actions, so this data is available. The general zend_registry is used for storing configuration, sharing variables and other information. Zend_register data will be erased every time a different page is requested.

Zend_session uses a session of PHP, can be shared by any page, it is really the scope of the session (that is, before the browser is closed, or the session expires before it is valid)

4. Zend_loader

People familiar with PHP know that in PHP, how to load the load (include) A class is a very troublesome topic, thus, PHP5 provides a __autoload mechanism to facilitate the automatic loading of class files. The Zend Framework also provides a functional zend_loader that enables dynamic loading of files and classes.

Provides methods available for loading features of Zend_loader:

L Loading files

Zend_loader::loadfile ($filename, $dirs =null, $once =false);

$filename is the name of the file to be loaded, $dirs the directory where the file is located, if it is empty, the program will be automatically found in PHP include_path, $once Specify whether to load only once, true load once, otherwise, load repeatedly. If loadfile fails to load the file, this method throws a Zend_exception exception.

L Load PHP class

Zend_loader::loadclass ($class, $dirs) can also support loading of PHP classes, where $class is the class name, $dirs is the path and file name of the containing class, and this method corresponds to the file of the directory according to the underscore Zend_ Controller_action will point to the zend/controller/action.php file. If $dirs is a string or an array, the method finds the corresponding directory in order, loads the first matching file, and finds it in include_path if it is not found.

5. Zend_acl

The Zend_acl component provides a solution for implementing a complete access control, which defines two important conceptual resources and roles in Zend_acl, and the corresponding two Zend controls are Zend_acl_role and Zend_acl_resource respectively.

Zend_acl_resource: In Zend_acl, any file can be treated as a resource, Zend_acl also provides a tree structure of resources, which can be freely added to many resources. ZEND_ACL also supports resources-based create,read,update and delete permission waits. Resources can be implemented by implementing Zend_acl_resource_interface, while Zend_acl_resource is a basic Resource implementation and can be extended to implement resources

Zend_acl_role: In Zend_acl, a role is a general term for all objects that are accessed, and roles can have inheritance relationships, which can be developed roles through Zend_acl_role_interface interfaces, as well as Zend_acl_ Role is a basic role implementation that can be used to inherit an extension

Ways to create ACLs

$acl =newzend_acl ();

$acl->addrole ($roles, $parentnode);//Join the role

$acl->allow ($roles, $resources, $privilege, $assert);//Specify the user group $roles permissions on $resources, $resources use NULL to represent all resources, $ Privilege can be create,edit,delete and so on, and $assert is used to specify controls that have specific constraints, such as not allowing for a certain period of time.

$acl->deny ($roles, $resources, $privilege, $assert);//Add Deny permission on $resources for the specified user group $roles

Once the ACL is defined, we can use the isallowed method of the ACL to check if a user has permission on a resource, as

$acl->isallowed ($roles, $resources, $privilege);

6. Zend_auth

Access the authentication adapter to give a way to authenticate user access, Zend_auth rely on a specific authentication service for authentication (e.g. RDBMS)

Zend_auth provides many kinds of system default authentication access support, which is now simply a description of the database authentication method.

Zend_auth_adapter_dbtable is the database access scheme provided by Zend_auth, and its default constructor parameters need to be:

L $ZENDDB, an example of an zend_db_adapter adapter

L $tableName, the table name of the database

L $identityColumn: Specify the column of records in the table

L $credentialColum: Specify the columns in the table (password column)

L $credentialTreatment: Specifies cryptographic operations on a column in a table

1. The initialization of an object can also be as follows: (in the form of a set instead of a constructor parameter)

$dbAdapter = Zend_db_table::getdefaultadapter ();

$authAdapter = new Zend_auth_adapter_dbtable ($dbAdapter);

$authAdapter->settablename (' Zendlogin ')

->setidentitycolumn (' username ')

->setcredentialcolumn (' password ')

->setcredentialtreatment (' MD5 (?) ');

2. After the object is initialized, you can call the

$auth->setidentity (username);

$auth->setcredential (password);

$result = $auth->authenticate ();

If ($result->isvalid ()) {

...

The default storage is a Sessionwith namespace Zend_auth

$authStorage = $auth->getstorage ();

$authStorage->write ($userInfo);

}

The user is authenticated.

3. And when the user exits, it can be used:

Zend_auth::getinstance ()->clearidentity ();

Clears the saved authentication information.

(After the user has successfully passed the authentication, it is necessary to set up a persistent authentication, which uses the zend_auth_storage_session to implement the authentication information saving function by default in Zend_auth.) )

7. Zend_log

A common log component is given in the Zend framework, Zend_log, which is responsible for the operation of various log preservation, which is divided into

Log object: an instance of Zend_log, a common object

Write object: Inheritance and zend_log_writer_abstract, responsible for saving data to storage

Filter object: Implements the Zend_log_filter_interface, filters some unwanted data

Formatter object: Implements the Zend_log_formatter_interface to format the log data before write writes to the data, with only one Formatter object per writer

Only the Zend_log object is described below.

How to use it broadly:

$writer =newzend_log_writer_stream (' Log.txt ');//Initialize Zend_log_writer_stream instance

$log =newzend_log ($writer); Initializing the Zend_log object

$log->log (' Someitems ' Zend_log::alert); To write data to the log, using the alert message level, you can use a number of message levels ... Check online for details.

Zendframework Getting Started Tutorial

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.