Zendframework2 tutorial [2]-read data

Source: Internet
Author: User
Tags autoload php foreach
This tutorial may take a long time. You need to be patient and read the article. The source code is downloaded at the end of the article. The webmaster recommends that you download the source code and check it against the tutorial, which will be smoother. Zf2 uses a module system to organize and manage your main Application code in each module. In the previous tutorial, the Application module is used to provide bootstrapping to the entire Application and handle errors.

This tutorial may take a long time. You need to be patient and read the article. The source code is downloaded at the end of the article. The webmaster recommends that you download the source code and check it against the tutorial, which will be smoother. Zf2 uses a module system to organize and manage your main Application code in each module. In the previous tutorial, the Application module is used to provide bootstrapping to the entire Application and handle errors.

This tutorial may take a long time. You need to be patient and read the article. The source code is downloaded at the end of the article. The webmaster recommends that you download the source code and check it against the tutorial, which will be smoother.

Zf2 uses the module system to organize and manage your main Application code in each module. In the previous tutorial, the Application module is used to provide bootstrapping, error processing, and route control for the entire Application. It usually provides the application layer controller for the homepage of each application, but we will not use this default module in this tutorial, because we want the album list as our homepage, this will be done by the modules we have created.

We will place all the code in the Album module, including controllers, models, forms, and views. Of course, they are configured. We will adjust the Application module as needed.

First, create a Module Directory.

Create a directory named Album in the module Directory. The structure is as follows:

Zf // module/Album/config/src/Album/Controller/Form/Model/view/album as you can see, the Album module allocates independent directories for different types of files we create. The PHP file containing classes in the Album namespace is located in the src/Album directory, so we can have multiple namespaces in our module as needed. The view directory also has a subdirectory named album, which stores our view scripts. Zf2 provides a ModuleManager [module manager] to load and configure modules. It will search for the module in module/album in module root directory [here is module/album. php, and you want to find a class named module in the file. This means that the class in the known module will have the namespace of the module name, that is, the name of the module directory. Create Module. php In the Album Module: Create Module. php In The zf/Module/Album directory:
 Array (_ DIR __. '/autoload_classmap.php',), 'zend \ Loader \ StandardAutoloader '=> array ('namespaces' => array (_ NAMESPACE _ => _ DIR __. '/src /'. _ NAMESPACE __,),),);} public function getConfig () {return include _ DIR __. '/config/module. config. php ';} module manager will automatically call for usGetAutoloaderConfig () andGetConfig () method. The getAutoloaderConfig () method returns an array compatible with zf2 AutoloaderFactory. To configure it, we need to add a class ing file to ClassmapAutoloader and add the namespace of this module to StandardAutoloader [standard automatic loader ]. StandardAutoloader requires a namespace and path to find the file. It follows the PSR-0 standard, so the ing rules for class names to file names are the same as for every rule in the PSR-0 rules. Because we are developing, we do not need to use class ing to load files. Therefore, we provide an empty array for the class ing automatic loader and create a file named autoload_classmap.php in the Module/Album directory. The Code is as follows:
 StandardAutoloader [standard automatic loader ]. After registering the automatic loader, let's take a look at the getConfig () method. This method only loads the config/module. config. php file. Create a file named module. config. php In the module/Album/config directory:
 Array ('invokables '=> array ('album \ Controller \ Album' => 'album \ Controller \ albumcontroller ',),), 'view _ manager' => array ('template _ path_stack' => array ('alipay' => _ DIR __. '/.. /view',); configuration information will be passed to related components by ServiceManager [Service Manager]. We need two initial parts:Controllers [controller] andView_manager [view Manager ]. The controller section displays the list of all controllers provided by the module. We will need a controller: AlbumController. The Controller name is referenced by the key name "Album \ Controller \ Album". The Controller name must be unique in the entire module. Therefore, we add a prefix for it-our module name. In the view_manager section, we will add our view directoryTemplatePathStack option, which allows it to find the view Script of the Album module in our view directory. Now we need to tell ModuleManager [module manager] that this new module exists. We can complete this work in the config/application. config. php file and update this file. Then its modules will contain the Album module, so the current content of this file should be as follows:
 Array ('application', 'alipay', // <-- this is the row we need to add ), 'module _ listener_options' => array ('config _ glob_paths '=> array ('config/autoload /{,*.} {global, local }. php ',), 'module _ paths' => array ('. /module ','. /vendor ',),),);
As you can see, we add the Album module to the Application module. Now we can add custom code for our module. We will build a very simple inventory list system to show our album collections. On the home page, we will list album sets and allow us to add, modify, and delete them. We will need the following pages:
Page Description
Home Page The real album list also provides links for modification and deletion. There is also a link to add a new album.
Add new album This page allows us to add new albums.
Edit album This page provides a form to edit the album.
Delete album This page will confirm that we want to delete an album and finally delete it.
Before we build our files, it is very important to understand how the framework organizes pages. Every page in the application is regarded as an action, and all actions are in the module controller. Therefore, in general, you need to organize related actions into the corresponding controller. For example, a new controller may contain actions:Current,ArchivedAndView.Because our Album system contains four pages, we will organize them toThe AlbumController controller serves as four actions. As follows:
Page Controller Action
Home Page AlbumController Index
Add new album AlbumController Add
Edit album AlbumController Edit
Delete album AlbumController Delete
The ing from URL to action is completed by routing. You canDefine routes in the module. config. php file. We will define routes for actions. The following are configured
In the module. config. php file, the highlighted part is newly added:
 Array ('invokables '=> array ('album \ Controller \ Album' => 'album \ Controller \ albumcontroller',),), // The following section is newly added, you should add them to your own files 'router' => array ('routes '=> array ('album' => array ('type' => 'segment', 'options' => array ('route '=>'/album [/: action] [/: id] ', 'constraints' => array ('action' => '[a-zA-Z] [a-zA-Z0-9 _-] *', 'id' => '[0-9] +',), 'defaults' => array ('controller' => 'album \ controller \ Album ', 'action' => 'index ',),),),),), 'view _ manager' => array ('template _ path_stack' => array ('alipay' => _ DIR __. '/.. /view ',),),);
The route name is album. The type [type] Is segment. The segment [segment] Route allows us to identify placeholders in the url and map these placeholders to parameters in the matched route. The current condition is:/album [/: action] [/: id], which will match any url starting with/album, the next segment will be the name of an optional action, and the next one will be mapped to an optional id. Square brackets indicate that a segment is optional. The constraints section limits the segment characters as expected. Here we limit action to start with a letter, and the subsequent characters can only be letters, underscores, or asterisks. We limit the id to a number. This route will allow us to own the following url:
URL Page Action
/Album Home Page Index
/Album/add Add new album Add
/Album/edit/2 Use id2 to edit an album Edit
/Album/delete/4 Use id4 to delete an album Delete

In zf2, the Controller is a class called {Controllername} Controller. {Controllername} must start with an uppercase letter.In the {Controllername} Controller. php file, this file is located in the module'sController directory. Here, module/Album/src/Album/Controller. Each action is a public method in the Controller and is named in the form of {Action name} action. Here {action name} should start with a lowercase letter.

Let's create our control class in the zf/module/Album/src/Album/Controller directory:The code for AlbumController. php is as follows:

 
 
 
URL Method called
Http: // localhost/zf/public/album Album \ Controller \ AlbumController: indexAction
Http: // localhost/zf/public/album/add Album \ Controller \ AlbumController: addAction
Http: // localhost/zf/public/album/edit Album \ Controller \ AlbumController: editAction
Http: // localhost/zf/public/album/delete Album \ Controller \ AlbumController: deleteAction

We now have an available vro and have created an action for each page of the application.

Now it is time to create a view and model layer.

To integrate a view into our application, we need to create a view script file. These files will be executed by defaviewviewstrategy [default view policy] and can be passed to any variable or view MODEL returned by the Controller action method. These view scripts are stored in the view directory of our module. The directory name is the same as the controller directory name. Create the following four empty view files:

  • Module/Album/view/album/index. phtml
  • Module/Album/view/album/add. phtml
  • Module/Album/view/album/edit. phtml
  • Module/Album/view/album/delete. phtml

Now we can fill in any content to it, and then start to use the database and model.

Create a database named zf and use the following statement to create a data table and insert the test data:

Create table album (id int (11) not null auto_increment, artist varchar (100) not null, title varchar (100) not null, primary key (id )); insert into album (artist, title) VALUES ('the Military Wives ', 'In My Dreams'); insert into album (artist, title) VALUES ('adre ', '21'); insert into album (artist, title) VALUES ('Bruce springsteen', 'wrecking Ball (Deluxe) '); insert into album (artist, title) VALUES ('Lana Del Rey ', 'born To die'); insert into album (artist, title) VALUES ('gotye', 'making Mirrors '); we will use the php pdo driver. Now we have some test data in the database, and we can write a very simple model for it. Zf2 does not provide a Zend \ Model component, because model is your own business logic and you decide how it works. Depending on your needs, there are many other components for you to choose from. One method is to let your model class present each object in the application, and then use the ing object to load and save the object content to the database. Another method is to use ORM, like Doctrine or Propel. In this tutorial, we will use the Zend \ Db \ TableGateway class to create a very simple model-AlbumTable class. In TableGateway, each album object is an Album object [entity], which is a deployment method of "table data gateway design mode". It allows us to access data in a table in the database. However, the table data gateway design mode may become a bottleneck in a large system. You may want to place the database access code in a controller action method, because these are displayed inIn Zend \ Db \ TableGateway \ AbstractTableGateway, The zf2 development team strongly recommends that you do not do this! Now we areModule/Album/src/Album/Model: Create a file named Album. php in the directory. The Code is as follows:
  Id = (isset ($ data ['id'])? $ Data ['id']: null; $ this-> artist = (isset ($ data ['artlist'])? $ Data ['artlist']: null; $ this-> title = (isset ($ data ['title'])? $ Data ['title']: null;} our Album object is a simple php class. To make itZend \ Db'STableGateway works together and we need to implement an exchangeArray () method. This method copies the data transmitted from the array to the attributes of the object. Later, we will add an input filter for our form. Next, create AlbumTable. php In the module/Album/src/Album/Model directory. The Code is as follows:
  TableGateway = $ tableGateway;} public function fetchAll () {$ resultSet = $ this-> tableGateway-> select (); return $ resultSet;} public function getAlbum ($ id) {$ id = (int) $ id; $ rowset = $ this-> tableGateway-> select (array ('id' => $ id )); $ row = $ rowset-> current (); if (! $ Row) {throw new \ Exception ("cocould not find row $ id");} return $ row;} public function saveAlbum (Album $ album) {$ data = array ('artlist' => $ album-> artist, 'title' => $ album-> title,); $ id = (int) $ album-> id; if ($ id = 0) {$ this-> tableGateway-> insert ($ data );} else {if ($ this-> getAlbum ($ id) {$ this-> tableGateway-> update ($ data, array ('id' => $ id ));} else {throw new \ Exception ('form id does no T exist ') ;}} public function deleteAlbum ($ id) {$ this-> tableGateway-> delete (array ('id' => $ id ));}} we still have a lot to do. First, we need to set an access rule for the TableGateway object to the protected attribute $ tableGateway, which is passed to the constructor. We will use this class to operate databases for our album system. Next, we will create some methods for applications to interact with the table data gateway,The fetchAll () method obtains all album records from the database. The type is ResultSet [result set ]. The getAlbum () method obtains a single row of records as an Album object. The saveAlbum () method can create a new record or update an existing record in the database. DeleteAlbum () deletes a record. The code meaning of these methods is of course self-evident. To always be able to use the same instance of the AlbumTable object, we will use ServiceManager [Service Manager] to define how to create an instance. This is the easiest way to complete a model class. In the class, we create a getServiceConfig () method, which will beModuleManager is automatically called and applied to ServiceManager. When we need it, we can get it again. To configure ServiceManager, we can provide the name of the class to be instantiated or the factory (closure or callback function) of the instantiated object as needed by ServiceManager ). First, implement the getServiceConfig () method, which provides a factory for creating AlbumTable. Add this methodThe bottom of Module. php, located in module/Album.
  Array ('album \ Model \ albumtable' => function ($ sm) {$ tableGateway = $ sm-> get ('albumtablegateway '); $ table = new AlbumTable ($ tableGateway); return $ table;}, 'albumtablegateway' => function ($ sm) {$ dbAdapter = $ sm-> get ('zend \ Db \ Adapter '); $ resultSetPrototype = new ResultSet (); $ resultSetPrototype-> setArrayObjectPrototype (new Album (); return new TableGateway ('alipay', $ dbAdapter, null, $ resul TSetPrototype) ;},),) ;}this method returns a factory array, which is integrated by ModuleManager before being passed to ServiceManager. The factory of Album \ Model \ AlbumTable uses ServiceManager to create an AlbumTableGateway passed to AlbumTable. We also told ServiceManager that an AlbumTableGateway is created by obtaining Zend \ Db \ Adapter [This is also obtained from ServiceManager]. We will use AlbumTableGateway to create a TableGateway object.OnceTableGateway creates a new result row and is notified to use an Album object. The TableGateway class uses the prototype when creating a result set and an object. This means that, when necessary, the system will clone an object pre-instantiated. View PHP Constructor Best Practices and the Prototype Pattern for more details. Finally, we need to configure ServiceManager so that it knows how to obtainZend \ Db \ Adapter. We will use a factory named Zend \ Db \ Adapter \ AdapterServiceFactory to complete this configuration. We can configure this factory in the built-in Configuration System. Zf2ModuleManagerThe module. config. php file integrates all the configurations and then integrates them intoConfig/autoload(*. Global. phpAnd then*. Local. phpFiles. We will add database configuration information to global. php, which you should submit to your version control system. In addition to CVS, you can use local. php to store creden。 for your database (that is, the user name and password), if you want to do so. Modify zf/config/autoload/global. php as follows:
   array(        'driver'         => 'Pdo',        'dsn'            => 'mysql:dbname=zf2tutorial;host=localhost',        'driver_options' => array(            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''        ),    ),    'service_manager' => array(        'factories' => array(            'Zend\Db\Adapter\Adapter'                    => 'Zend\Db\Adapter\AdapterServiceFactory',        ),    ),);
You should store your database creden In the config/autoload/local. php file so that they are not located in the git repository [becauseLocal. php is ignored.]
  Array ('username' => 'your username HERE ', 'Password' => 'your password HERE',),); nowServiceManager has created an AlbumTable instance for us. We can add a method to the Controller to obtain it. SetGetAlbumTable ()Add methodAlbumController controller class:
// Module/Album/src/Album/Controller/AlbumController. php: public function getAlbumTable () {if (! $ This-> albumTable) {$ sm = $ this-> getServiceLocator (); $ this-> albumTable = $ sm-> get ('album \ Model \ albumtable ');} return $ this-> albumTable;} at the top of the class, you should also add: protected $ albumTable; now, when we need to interact with the model, we can call the getAlbumTable () method from the Controller. For the real album list, we need to obtain them from the model and pass them to the view. To achieve this goal, we need to implement the indexAction () method in the AlbumController controller. UpdateAlbumControllerThe indexAction () method is as follows:
// Module/Album/src/Album/Controller/AlbumController. php ://... public function indexAction () {return new ViewModel (array ('alums' => $ this-> getAlbumTable ()-> fetchAll (),));}//... when zf2 is used, to set variables in the view, we return a ViewModel instance. The first parameter of the constructor of this model instance is an array from actions, this includes the required data, which will be automatically passed to the View Script. The ViewModel object also allows us to change the used View Script. However, by default, {controller name}/{action name} is used. Now we can complete the index. phtml View Script.

// module/Album/view/album/album/index.phtml:

$ Title = 'my albums ';
$ This-> headTitle ($ title );
?>
EscapeHtml ($ title);?>


Url ('alipay', array ('action' => 'add');?> "> Add new album














Title Artist  
EscapeHtml ($ album-> title);?> EscapeHtml ($ album-> artist);?>
Url ('alipay ',
Array ('action' => 'edit', 'id' => $ album-> id);?> "> Edit
Url ('alipay ',
Array ('action' => 'delete', 'id' => $ album-> id);?> "> Delete

The first thing we need to do is to use the headTitle () view help function to set the title of the page and the title of the head part. This function will be the title bar of the real browser. Next, we will create a link to add a new album.

The url () view help function is provided by zf2 and used to create the link we need. The first parameter is the route name we want to use to construct the url. The second parameter is an array that contains all the variables to be filled with placeholders: it is actually the name of the action ]. Here, we use album routing, which is set to accept two placeholders: action and id.

We assign the variable $ albums from the controlled action. The zf2 view system will automatically ensure that these variables are released to the View Script range. Therefore, we do not need to worry about using the $ this-> prefix as in zf1 to obtain their values. However, you can still do this if you like.

Next, we will create a table to show the title and author of the album and provide links for editing and deleting records. A standard foreach loop is used to traverse the album list. We use the replacement syntax colon andEndforeach; because this is easier than using curly braces. The url () view help function is used again to create links for editing and deletion.

Note: We always useThe escapeHtml () view helps functions to avoid XSS [Cross-Site Scripting] attacks ].

Now, if you browse http: // localhost/zf/public/album, you will see the album list.

Source code download: http://pan.baidu.com/share/link? Consumer id = 272621 & uk = 2585386604

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.