Develop professional web applications with Kohana

 0  0  344  2019-03-16 06:36:51 Laporkan dokumen yang dilanggar

Paul Liversidge

  I'd like to thank my wife and kids for allowing me to steal some time from them to review this book and my poor despondent dog that lost out onhis long walks in the park. I'd also like to say a big thank you to Woody Gilk(Shadowhand) for sharing Kohana with the wider community, and I hope that my own involvement in reviewing this book has helped to widen theusage of Kohana.

Brief history of Kohana

  If you have experience with Kohana 2, and would like to see the differences in more details, and understand the process of moving from Kohana 2 to Kohana 3, please take at look at the Appendix: Upgrading from CodeIgniter and Kohana 2 . Most importantly, it includes the API reference, which allows easily us to explore and view the methods and properties of every class in the library see.

Structure and patterns

  This is a great feature as wedo not have to write a lot of or statements, and it eliminates the include() require() need for trying to find files before we can use them. All we need to do to extend it in our application is to drop a file with the same name into our application directory structure,and we can begin extending and overloading the class.

HMVC in a nutshell

  The advantages of using Object-OrientedProgramming (OOP) were recognized with the release of PHP 5, and the development community quickly began finding ways to create more reusable, lightweight, and expandablecode. Where MVCs allow for one controller to be loaded and executed, the HMVC pattern loads a primary controller, and then allows requests to be created repeating the loop of routing andloading controllers, and allowing for even more requests.

Models, Views, and Controllers

  Our controllers are loaded immediately after the request, and will delegate data modeling to our models, and presentation duties to our views. View files shouldcontain the least amount of PHP code of the three types, and should utilize PHP's alternative syntax for control structures when it is necessary to use server-sidescripting.

Alternative syntax

  Chapter 6 , Interacting with the Database, will take a more detailed look at the Database and ORM modules, their use, and a more in depth look at some of the official modules that use and rely on these very important modules. Chapter 8 , Troubleshooting and Error Handling, will be covering troubleshooting and error handling, and we will be able to see how to detect and debug errors in our applicationswhile adding the final touches to the case study site.

Case Study

  The website makes it very easy to obtain and install the most current stable release of Kohana, browse the documentation, and interact with the Kohana community. Although installing Kohana via the download archive is a quick and easy way of obtaining the framework, the code repository is hosted and maintained on GitHub ( http://github. ), and can be accessed and updated via this resource.

Installing Kohana from GitHub

  The Git clone available at https://github.com/kohana/kohana.git tells Git to clone, or to make an exact copy of, the repository located at https://github.com/kohana/ , the second argument, tells GitHub which branch you want kohana.git –b 3.0/master to clone, and the final argument tells Git where to place the cloned repository, in this case the directory. $ chmod -R 777 application/cache $ chmod -R 777 application/logs Getting Started While changing the permissions for your cache and logs on your development environment to full access to all users, on your production servers you will want to enforce a bit ofsecurity, and your web server should be the owner or a member of the group with write access to this directory.

Configuring Kohana for Development Environment

  Let's remove the comments for the 'userguide' module so your code block looks like this: Kohana::DEVELOPMENT Time for action – Enabling the User Guide Lastly you will want to look at the Kohana::modules method, and the array of options that are commented out. When you prepare your application for deployment on your production server, you will want to change the value of Kohana::PRODUCTION and file and see what it takes to get a basic configuration file in place so you can keep your application's options in one, easy to find place.

Testing your configuration

  You know your setup is working correctly by viewing thispage for three reasons: ‹ Our modules are configured correctly, or you cannot see the User Guide ‹ Our .htaccess are set up right, or you would need index.php in the URL ‹bootstrap.php is also properly configured If you are unable to view the User Guide from your local installation, be sure to check the settings in your and files. In this chapter, we will: ‹ Learn the anatomy of a view file ‹ Learn the anatomy of a controller‹ Create and extend controllers ‹ Create and use controller actions‹ Create view files ‹ Implement templates‹ Create an application controller By the end of this chapter, we will have created controllers and views, utilized Kohana's template system, leveraged some of the power of the HMVC pattern, and used it all togetherto bring our first bit of interactivity to the case study site.

What are controllers and views?

  Simply put, controllers handle the request and pass data between models and views, while views display the output for the user. For this chapter, we will be working in the application directoryof our site root, and we will work with modules later in Chapter 5.

Anatomy of a view

  Any method in a class in Kohana that is public, and prefixed with Controlleraction_ is considered a Controller Action and can be directly accessed by our users, and it is the method that will perform tasks for our applications. This is why the output of the Welcome_Controlleraction_ method is called when we do not specify anything in our URI.index() Finally, inside our action_index() method, we see: $this->request->response = 'hello, world!'; This line sets the response to a string of 'hello, world!', and it is then displayed on the screen for all to see.

Passing data to the view

  This set() could also be written with the same outcome as: public function action_index() {$view = View::factory('welcome'); $view->set('site_name', 'Egotist');$view->set('random', rand(1,10)); $this->request->response = $view;} Using the method makes it easy to read code, and can be a good pattern to use when set() the values for the view variables will be computed elsewhere, and then set once the view is instantiated. In the view script, we are now checking for the existence of prior to displaying $site_name it, and defaulting to "Egotist" if the is not specified.$site_name Removing the following line of code in our Welcome Controller's method action_index() will prevent $site_name from being set as a view variable: $view->site_name = 'Egotist Beta'; A quick refresh would show that the app did not break, because we were checking to make sure the variable was set before we printed it out.

Have a go hero – Explore controllers and view variables

  In the index action we assigned some view variables to the content view that are only accessible in the view file, as that is the object on which they are set. welcome.php With our template, we may want to add the ability to set the page title from the controller, and have it displayed in the <head> section of our template file.

Binding global view variables

  By binding the $site_nameglobal view variable, we were able to pass the variable by reference, and then $site_name set it later in the controller without having to re-assign it to the view. Because we were just changing the way we passed the variable, and not the name of the variable itself, there were no changes necessary in our view files.

Beyond the Welcome Controller

  This could be navigation items, document titles, generated keywords, or any other informationthat may be set in every controller to be used in the template. Before we can create a new controller to sit between the Template Controller and the controllers with which we will build our application, we need to know how to create a newcontroller from scratch.

Creating new controllers

  By simply creating another controller action and following the naming conventions, we were able to add another page by just creating the viewcontent, setting the global view variable, and calling the view file for the page in question. When we cover routing and request handling in more detail, we will get a more involved look into methodslike before() and after() , but for now it is okay to think of the before() method as a sort of constructor, or a method that will be run before any other methods in the controller.

Putting it all together

  Now that we have some experience creating views and controllers in Kohana, and have seen some of the patterns that can be used to make coding in Kohana easier, it is time to applysome of this knowledge and fix up the Egotist case study application. Apart from rendering the header and footer views from within the template view, most of theadditional code in the file should be self-explanatory; let's take a look at the template.php header view render, which is new to us: <?phpechoView::factory('common/header'); ?> We have encountered the static method a few times already, and know View::factory() that it returns a new View object using the view file passed to it.

Have a go hero – Customize quickly and easily

Summary When we began this chapter, our Kohana application was installed, but did not do much

  Now that the application is showing some signs of life, and we have a good grasp on how the template, controllers, views, and file system are all working together to deliver rich contentwith little code, we can now begin to customize our application's look and feel. Now that we have installed Kohana and created our first views and controllers, it is time to take a look at the inner workings of the framework, so we will have the knowledge necessaryto create web applications that take advantage of Kohana’s most powerful features.

Hierarchy is King in Kohana

  This means the framework loads files for each of it’s core parts in a hierarchical order, which is explainedin more detail in just a bit. These features are thefoundation of HMVC, which essentially is a cascading filesystem, flexible routing and request handling, the ability to execute sub-requests combined with a standard MVC pattern.

Cascading filesystem

  These constants are index.php The Now that we have seen how the framework merges files to create a set of files to load on request, it is a good place to see the flow of the files in Kohana. If no controller or action is passed in the URI on a vanilla Kohana install, the welcome controller will be loaded, and the index action invoked as outlined in the array passed to the Route::set() method in the boostrap.

Using the Request object

  The request flow in Kohana is interesting, and it is easy to see how it can be powerful on a high level, but the best way to understand HMVC and routing in Kohana is to look at someactual code, and see what the resulting outcome is for real world scenarios. The class declaration in this application/classes/controller/application.php controller looks like this: abstract class Controller_Application extends Controller_Template In this file, we can see the before() method loading the template view into the template variable, and in the method, we see the Request obeject ( ) after() $this->request having the response body set, ready to be rendered.

Creating a profile page to render messages In our case study site, users will be creating text messages that will be listed on the site

  Toprevent having to write this logic in several places inside the Egotist application, it is better to create a controller that handles the logic for listing messages for a user, and a view to listout the messages, and then have any pages that use the list to request it from within their corresponding actions. We are at one of the cross roads in application development, where we are best served by thinking about how the application could act in the future, and architect our code in such amanner to anticipate future needs while minimizing code complexity.

Calling a new request inside a request

  When we altered our Profile Controller class, we removed the logic that is now living in the Messages Controller, and replaced the view variable contents with this $messages line of code: $messages = Request::factory(‘messages/get_messages’)->execute()- >response; Here, we are calling the factory method on the Request object, and telling it to request the Messages Controller’s action. Routing in Kohana If you remember, the bootstrap file comes preconfigured with a default route that follows a very simple structure: Route::set(‘default’, ‘(<controller>(/<action>(/<id>)))’) This tells Kohana that when it parses the URL for any request, it first finds the , base_url and then the next segment will contain the controller, then the action, then an ID.

Creating friendly URLs using custom routes

  While this is great for finding a user by their ID, and the URL that a user would use to find the profile is nicer than it was before, it is still not as descriptive as it could be. If we linked to http://localhost/egotist/ profile/2/some-users-name , we would get an application error, as there is not a route that is defined that matches this scheme, and the default route will look for a method named in the profile controller, as defined in the default route in our bootstrap file.

Using subdirectories with routes

  prefix to Inside the new Controller_ directory, and will need to start with the class name Controller_User , based on the framework’s naming conventions for controllers. After moving our Profile and Messages Controllers inside a subdirectory named user, we had to open the files and change their class names to include their path, changing the classes/controller/user Inside our route named ‘profile’, we added an additional array key for directory in the defaults array settings, and assigned it the value of ‘user’.

Pop quiz – Understanding Routes and the Kohana Filesystem

  Even though most of the code added in this chapter was exampledata, when it comes time to adding information from the database, you will have the understanding necessary to manipulate the routes and requests to properly use that data. In short, the underscores are converted to slashes, the string is converted to lowercase, and the file is searched for in the classes/sub-directory of Kohana's cascading filesystem.

Introducing helpers

  We will refer to methods that provide the functionality ofhelpers in the traditional method, being formatting and providing additional functionality to standard features, as helpers in this chapter. There are a few helper classes that are commonly used in many applications, and we will take a look at how to use these more common classes in more detail.

The Date class

  Have a go hero – Customizing fuzzy date text You may create applications in the future that will use the fuzzy dates, but decide that you do not want to use the text that is currently used in the framework. Because you want to keepthe rest of the functionality of the Date class, you decide to override the fuzzy_span() function by extending the Date class inside your application.

The HTML Class

  To create an anchor using theHTML class, we can simply do this: <?php echo HTML::anchor('/welcome', 'Welcome Page'); ?> If added into our case study site, this would create the following HTML: The first parameter of is the URL for the link, the second an optional title, HTML::anchor() and the third allows for attributes to be assigned to the element. There are three parameters: the first is the file location, the second is an array of attributes, and the last is a tool that determines whether the index file should be prepended to the URL if a relative path isprovided.

The Arr (Array) Class

  It is very common for developers to set a default value for a variable, and then determine whether the variable was set via or (or other methods), and then replace $_GET $_POST the default value with a new one. A common use case for this may be to have the page passed as a parameter in the URL, GET and if none is given to default to page 1.<?php $page = Arr::get($_GET, 'page', 1); ?> This method saves a few lines of code every time a value is needed from an array, and if none is given, to have an elegant way to handle default values.

The Arr::range() method

  The first parameter is the increment, or step, that should be applied, and the second is for the maximum valueof the range. To count by twos, simple change the first value: <?php $range = Arr::range(2, 10); ?> Now, we can see that the range starts with 2, and contains all the even numbers through 10: array(5) { [2]=> int(2) [4]=> int(4) [6]=> int(6) [8]=> int(8) [10]=> int(10) } As we can see, the class is a nice addition to the functionality inherent in PHP.

The Cookie class

  Working with Helpers and Classes Printing out the contents of the global variable's value for our username cookie $_COOKIE will reveal the contents of the cookie: 84330a7f8b2fc797f215979f83ad38b4dbe81f53~jdstraughan If someone were to alter the jdstraughan portion of the cookie, it would not pass the validation in , and, by default, NULL would be returned in place of the Cookie::get() altered data. First, we need to remove the cookie's name and value from the global $_COOKIE variable, and then we need to set thecookie's value to NULL, and expire the cookie by setting the expiration value to a time in the past.

The Encrypt (Encryption) Class

  Working with Helpers and Classes Encrypt::instance() <?php $encrypt = Encrypt::instance();$encrypted_email = $encrypt->encode('super.secret.person@example.com'); $decrypted_email = $encrypt->decode($encrypted_email);echo $decrypted_email; ?> , and as you can guess, it uses the key to decrypt the data, returning the original information: decode() is encode() method returns an Encrypt object, we can chain methods for shorter code. The complimentary method to Because the Encoding, like all the other helper methods, is a simple one liner: <?php $email = Encrypt::instance()->encode('super.secret.person@ example.com'); ?> Because of the design pattern used in Encrypt, we cannot call the helper methods statically.

The Feed Class

  To create a new RSS/ATOM feed, the method just needs the array of feed Feed::create() info (title, date created, pubDate, etc.) for the first parameter, an array of items for the second, and optionally, we can pass the format (rss2, atom, rss) as the third. Once the database is in place for our case study site, we will be able to create the items array on the fly from our database.

The Form Class

  We just have to pass the name and an optional array of attributes to create a file upload field: <?php echo Form::file('avatar'); ?> The above code will produce: <input type="file" name="avatar" /> Creating select elements with the form helper is much more DRY, as we can just pass a name to , then an array of options, a default selected option, and the array of Form::select() attributes if we need. Like the login and signup pages, it will need a custom route so it can be accessed via ; it will need a controller action in the http://localhost/egotist/forgot_password account controller, and it will need a view with an explanation that an e-mail address must be entered into the form and instructions for getting a new password will be sent to them.

Anatomy of a Module

  Each of these modules is residing in the directory assignedto the constant, loaded the Kohana::modules() module so we could use the local guide, and to test the installation and server configuration. Specifically, take a The best way to illustrate the loading of the modules is to open and view your Loading and configuring modules Loading new modules into your application is extremely simple.

Bundled modules

  Installing and Configuring Modules Take the Database module for example; it is not absolutely necessary to run the framework, and some applications will not need a database, but many will. This module not only houses the default pages, it also allows for expansion by having pagesadded by enabled modules, and allows the API Browser to be built on the fly, keeping our project's documentation always up to date.

Image module

  Becauseof the level of abstraction used, we do not need to know the commands for GD orImageMagick; all we need to know is the methods available from the module, and then we can manipulate images programmatically, using a familiar syntax. Like all other bundled modules, we will need to enable the Image module by uncommenting the module in our bootstrap.php file in the array inKohana::modules().

Dokumen baru
Aktifitas terbaru
Penulis
123dok avatar

Berpartisipasi : 2019-03-13

Dokumen yang terkait
Tags
Testing Web Applications Expert Systems With Applications Expert Systems With Applications Journal

Develop With Tomorrow S Standards Today

Learning To Professional With Share Knowledge

Modern Pharmacology With Clinical Applications Pdf

Develop professional web applications with Ko..

Gratis

Feedback