1. Trang chủ
  2. » Công Nghệ Thông Tin

Expert PHP 5 Tools phần 7 potx

46 294 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 46
Dung lượng 1,01 MB

Nội dung

Chapter 6 [ 261 ] • Use of design patterns:  ° Model-View-Controller architecture  ° Data Access Objects (DAO)  ° Active Record • JavaScript support via jQuery • Internationalization and localization • Support for caching, logging, error handling, theming, authentication, authorization, form and input validation • Console applications • Web 2.0 widgets • Web services For more information on the project and to download a copy of its latest release version, you should visit their site here: http://www.yiiframework.com/ Zend Framework application All that theory is great as a foundation from which to start exploring and experimenting with the creation of actual framework-based applications. But what really serves to illustrate the usefulness of a framework is to build a small application that leverages a representative collection of the features provided by the framework. We can't really do this for more than one framework for the simple reason that this chapter would become too long. I would like to preemptively offer my apologies to all proponents of other PHP frameworks. However, since ZF has certainly become one of the most widely adopted frameworks, we will be using it for our project. The point of this exercise is to give you a whirlwind tour of some of the more commonly used components of ZF. We will see that we can achieve a lot of functionality without having to write a whole lot of code. If at some point, it seems like there is a lot of hand-waving going on, there are two reasons for that. First, we are leveraging a framework that is performing a lot of chores for us behind the scenes. We don't necessarily need or want to know all the details of what is going on, but without that knowledge it may seem a bit like magic. The second reason is that I am indeed skipping over many of the details of the various modules we will be using. There is not enough room to do an exhaustive treatment of the modules. Besides, that's not really the point of this chapter. However, for those who want to learn more about any of the ZF modules we will be using, I have enclosed links to the relevant sections in the excellent ZF Programmer's Reference Guide. Download from Wow! eBook www.WoweBook.com PHP Frameworks [ 262 ] For a more complete treatment of how to develop applications using ZF, you might also want to consult Keith Pope's Zend Framework 1.8 Web Application Development: http://www.packtpub.com/zend-framework-1-8-web-application- development/book Feature list We will create a simple website, complete with the following features: • MVC architecture • A templating engine • Database persistence • Logging • Authentication • A form • Email notication If it sounds like a tall order to tackle in one chapter, fear not because that is exactly why we're using a framework to do all the heavy lifting. Specically, the version of ZF I am using to create the application in this chapter is "Zend Framework Version: 1.9.3PL1". Application skeleton ZF comes with a module called Zend_Application to help you generate an application skeleton or augment existing applications with specic features. Since we are starting with a clean project, we will be using the create project option. Under the hood Zend_Application actually uses two other ZF modules to do the work, namely Zend_Tool_Framework and Zend_Tool_Project. Zend_Application is a command line executable that can be found in the bin directory of the top-most directory of the ZF distribution. In other words, if you download and extract the most recent Zend Framework, you will nd the bin directory just inside the main folder it created. Take a look at the following transcript where Zend_Application creates an application skeleton for us with just one command. In the bin directory of the ZF distribution, you will nd a couple of scripts that will handle the task of creating a blank project. The Unix/Linux/MacOS version is called zf.sh; whereas, the Windows equivalent is called zf.bat. Download from Wow! eBook www.WoweBook.com Chapter 6 [ 263 ] For lack of a better project name, I decided to use a sub-domain of my main domain name and call it zf.waferthin.com. This gives us a working skeleton of a website. There are only two things we want to do before ring up the web server and testing it out. Download from Wow! eBook www.WoweBook.com PHP Frameworks [ 264 ] First, we need to create a directory for log les. Later we will be adding a log le where the application can log exceptions and such, but for now we only need the logs directory for the Apache web server to store access and error logs. Storing the web server's log les inside the application's directory structure is not a requirement, but rather a preference of mine. If you prefer to have Apache write to log les somewhere else on the lesystem, you can skip this next step. Second, we need to create a symbolic link to the ZF inside the newly created site's library folder. I prefer to store larger libraries that will not be checked into my version control system outside of the main code base. Now let's take a look at what the site looks like from a browser: Download from Wow! eBook www.WoweBook.com Chapter 6 [ 265 ] Important concepts Before launching into an explanation of what all those directories and les that were generated automatically for us are, I think it will be helpful to cover some recurring concepts that help us tie things together. Bootstrapping Bootstrapping refers to the process of initializing the environment, components, and objects of the application. Bootstrapping is typically one of the rst things to occur when a request is being processed. With our setup as generated by Zend_Application previously, we will encounter a Bootstrap class that uses a conguration le and helper classes to perform the bootstrapping. MVC MVC is the acronym for Model-View-Controller, a frequently used design pattern to separate business logic, request handling and routing, and displaying of information from each other. Discussing MVC in detail is beyond the scope of this chapter. Besides, judging by the fact that you are reading this book, I will assume that you have come across MVC in your career as a developer. Nevertheless, if you need a quick refresher on MVC, you might want to read up on it at Wikipedia: http://en.wikipedia.org/wiki/Model-view-controller What is noteworthy at this point is that MVC is an integral part of the application skeleton we generated above. You will see it reected in the naming of the directories and classes. Application structure detail Let's take a look at the directory structure and les that were created automatically. If you look at the application directory, you will notice that aside from some additions, the components of the MVC pattern correspond directly to the contained directories. Here is a list of the directories, their purpose, and their default content. Model: application/models/ This directory is meant to contain classes that encapsulate business logic and DB mappings. By default, it is empty. Download from Wow! eBook www.WoweBook.com PHP Frameworks [ 266 ] View: application/views/ This directory contains views, which are responsible for displaying output and web pages to the user. Views are nothing more than HTML fragments interspersed by PHP. The sub-directories of application/views/scripts/ are named after the modules of the application. For instance, later in our application, we will create a users module, accessible at zf.waferthin.com/users/, which will have a corresponding users directory in the application/views/ directory. Views produce HTML fragments that are assembled by a layout into a complete HTML page (more about that later). By default, the application/views/scripts/ directory contains views for the errors and the index page. Controller: application/controllers/ This directory contains controller classes that correspond to the modules of the application. For example, the controller to handle requests from zf.waferthin. com/users would be called UsersController.php. Controllers handle user requests by instantiating models, asking them to perform certain actions, and displaying the result using views. By default, Zend_Application creates an error and an index controller. Conguration: application/congs/ This directory is meant to hold conguration les. By default, it contains the application.ini properties le with settings to initialize different environments: production, staging, testing, and development. This le is used by the bootstrapping process and classes. Based on the settings in this le the bootstrap process will set up the environment and initialize various components and objects. application/configs/application.ini [production] phpSettings.display_startup_errors = 0 phpSettings.display_errors = 0 includePaths.library = APPLICATION_PATH "/ /library" bootstrap.path = APPLICATION_PATH "/Bootstrap.php" bootstrap.class = "Bootstrap" resources.frontController.controllerDirectory = APPLICATION_PATH "/ controllers" [staging : production] [testing : production] Download from Wow! eBook www.WoweBook.com Chapter 6 [ 267 ] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1 [development : production] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1 Library The library directory starts out empty, but is meant to contain external dependencies. You may be used to naming this directory includes, classes, or something similar. In our simple example, the only library we really require is the Zend Framework itself. We already took care of that dependency by creating a symbolic link to ZF in the library directory. Public This is the only directory that should be directly accessible to the user's browser. Files in the public directory are meant to be viewed. This is where you would put all your static content, including but not limited to: • Images • CSS • JavaScript • Static HTML pages • Media: audio clips, video clips, and so on When conguring a web server such as Apache, the public directory is the equivalent of your DOCUMENT_ROOT. By default, Zend_Application creates two les in the public directory, .htaccess and index.php. The .htaccess le does two things. First, it sets the default environment. Second, it redirects all requests for les or directories that don't actually exist in the public directory to the index.php le. To do this, .htaccess requires the mod_rewrite Apache module to do some rules-based rewriting and redirecting. Here is the content of the .htaccess le: zf_waferthin.com/public/.htaccess SetEnv APPLICATION_ENV development RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d Download from Wow! eBook www.WoweBook.com PHP Frameworks [ 268 ] RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php [NC,L] The index.php le is the application's entry point. Here is the corresponding listing: zf_waferthin.com/public/index.php <?php // Define path to application directory defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/ / application')); // Define application environment defined('APPLICATION_ENV') || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production')); // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( realpath(APPLICATION_PATH . '/ /library'), get_include_path(), ))); /** Zend_Application */ require_once 'Zend/Application.php'; // Create application, bootstrap, and run $application = new Zend_Application( APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini' ); $application->bootstrap() ->run(); The index.php le denes the APPLICATION_PATH and APPLICATION_ENV constants that govern in which environment the application will run. It also sets the include path and uses Zend_Application to initialize the bootstrap process. Tests The tests directory is intended to contain unit tests. To start you off on the right foot, Zend_Application creates the sub-directories application and library, in which you are expected to create unit tests for the corresponding top-level directories of the application. By default, none of the unit tests are actually created. Download from Wow! eBook www.WoweBook.com Chapter 6 [ 269 ] Enhancements Now that we have a basic feel for the structure of the application, let's continue by adding some pages that showcase the functionality provided by Zend Framework. Adding a layout There are many interface elements that appear on the individual web pages that repeat throughout the site. Examples of these recurring sections are headers, footers, advertising sections, and so on. It doesn't make sense to repeat the code to generate those sections on every page. Earlier in this chapter, we encountered views that are responsible for formatting the information for display to the user. Although you can have a view generate a complete web page, it makes more sense to use views to generate the individual components and then assemble those components selectively to create the nal web page. This is where Zend_Layout ts into the picture. A layout represents a particular arrangement and combination of individual components (views). Although you can create any number of different layouts for a given site, we will concentrate on creating a single layout that will be used throughout the site. Our layout will have a header, footer, navigation, and a main content area. Visually, our layout breaks our pages into the following sections. Download from Wow! eBook www.WoweBook.com PHP Frameworks [ 270 ] We start by creating a new directory for layout scripts, application/layouts/ scripts/. There, we then create our layout script. Here is the listing. Application/layout/scripts/layout.pthml <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/ xhtml1-transitional.dtd"> <html> <head> <link rel="stylesheet" type="text/css" href="/style.css" /> <?php echo $this->headTitle() ?> <?php echo $this->headScript() ?> <?php echo $this->headStyle() ?> </head> <body> <?php echo $this->render('header.phtml') ?> <?php echo $this->render('navigation.phtml') ?> <div id="maincontent"> <?php echo $this->layout()->content ?> </div> <?php echo $this->render('footer.phtml') ?> </body> </html> The HTML in the above listing reects the wireframe we diagrammed earlier. The body of the page consists of the header at the top, a navigation column on the left, the main content area to the right, and the footer at the bottom. You will also notice that we are referencing a stylesheet in the head section of the document, which takes care of some basic formatting, such as positioning the navigation and main content areas next to each other. Another important thing to notice is the le extension of .phtml used for the previous listing, which is what Zend Framework's MVC implementation expects when looking for view templates. The above layout references various views, such as header.phtml, navigation.phtml, and footer.phtml. We will see where and how to create those in the next section where we take a look at views. In the above listing, you will notice that we are using more than one object and method for populating the HTML template with content. Let's start with the render() method, which is provided to us by Zend_View. This method takes a view template, renders it, and returns the output, which makes it possible to nest views. In the above listing, we are asking Zend_View to render the footer.phtml view and include its output. Download from Wow! eBook www.WoweBook.com [...]... users as an object in PHP Since we are dealing with user accounts, some of the actions our model will be expected to perform have to do with account creation, checking of login credentials, and validating input data Models live in the application/models/ directory Here now is the listing for the Model_Users class: application/models/Model_Users .php < ?php /** * Model_Users [ 278 ] Download from Wow!... Password (again): First Name: Last Name: message as $message) { echo "$message\n"; } [ 272 ] Download from Wow! eBook www.WoweBook.com Chapter 6 ?> Login: Password:... $this->getInvokeArg('bootstrap')->getResource('log')->log('Logging application startup.')); For more detail about the Zend_Log module, consult the following ZF manual page: http://framework.zend.com/manual/en/zend.log.html [ 2 75 ] Download from Wow! eBook www.WoweBook.com PHP Frameworks Adding a database After creating a view, we have a way for users to enter their information into a form However, we know that we will need to persist this account... database resource Add the following lines to your application.ini file, but substitute the credentials applicable to the database you created: application/configs/application.ini [ 277 ] Download from Wow! eBook www.WoweBook.com PHP Frameworks resources.db.adapter = "pdo_mysql" resources.db.params.host = "localhost" resources.db.params.username = "" resources.db.params.password = ""... application/views/scripts/users/signup.phtml < ?php foreach ($this->message as $message) { echo "$message\n"; } ?> Email: Password: '', 'basePath' => dirname( . www.WoweBook.com Chapter 6 [ 2 67 ] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1 [development : production] phpSettings.display_startup_errors = 1 phpSettings.display_errors. href="/style.css" /> < ?php echo $this->headTitle() ?> < ?php echo $this->headScript() ?> < ?php echo $this->headStyle() ?> </head> <body> < ?php echo $this->render('header.phtml'). %{REQUEST_FILENAME} -d Download from Wow! eBook www.WoweBook.com PHP Frameworks [ 268 ] RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index .php [NC,L] The index .php le is the application's entry point. Here

Ngày đăng: 12/08/2014, 16:21