📜 ⬆️ ⬇️

Introducing Kohana 3.0 - Parts 7, 8, 9

Meet the seventh, eighth and ninth parts of a series of articles on development with Kohana PHP V3 (KO3). Previous parts can be found under the tag " familiarity with kohana 3.0 ". In this 3-in-1 article, we will look at helpers (helpers), modules, and the use of third-party libraries.

Part 7: Helpers


The Kohana 2.0 documentation provides the following definition for them:
Helpers are handy features that are designed to help you with development.

They are similar to library functions, but there is a slight difference. In the case of libraries, it is necessary to create an instance of the library class in order to use its methods. Helpers are static class methods that are automatically loaded by the framework, so there is no need to perform additional actions.

That is, in essence, these are static methods made to “help” you with routine things, like working with arrays or URLs. Kohana has a number of ready-made assistants , but we will create our own. Open the editor and get started.

Create a new “helper” folder in “/ application / classes”. Open a new file and place the following there:
')
<?php class Helper_MyUrl { public static function SEOIt($str) { $str = preg_replace(array('/\s/', '/[$.+!*\'(),"]/'), array('-', ""), $str); return $str; } } 

Save it as “myurl.php” in the newly created directory “/ application / classes / helper”. Now open “/application/views/pages/ko3.php” and add this line to the end:

 <br /><?php echo Helper_MyUrl::SEOIt('This Is a string!!!');?> 

After saving, opening “http: // localhost / mykohana3 / ko3 /” in the browser, you will see “ThisIsastring” below. Pretty simple!

Translator’s note: this is not an article break; it’s just that this part is really indecently short. I can do nothing, sorry!

Part 8: Modules


A module is a plugin that can expand the core of the framework, give your project a new section (blogs and forums, for example) or simply provide a set of classes that are available globally. Let's start!

Create a new directory called “fortune” in the “modules” folder. Inside the “module / fortune” create the “classes” and “views” folders. Then in “/ module / fortune / classes” create a folder “kohana”, and in “/ module / fortune / views” create “fortune”. The directory tree should look something like this:

 modules +-- fortune |-- classes | +-- kohana +-- views +-- fortune 

In the folder “/ module / fortune / classes /” create the file “fortune.php” and put the following into it:

 <?php defined('SYSPATH') or die('No direct script access.'); class Fortune extends Kohana_Fortune{} 

Here we simply inherit the class that we will create further. Open a new document and copy the code there:

 <?php defined('SYSPATH') or die('No direct script access.'); /** * Fortune Cookie Module */ class Kohana_Fortune { // Merged configuration settings protected $config = array('view' => 'fortune/default'); protected $fortune = ""; /** * Creates a new Fortune object. * * @return Fortune */ public static function factory(array $config = array()) { return new Fortune($config); } public function __construct(array $config = array()) { // Overwrite system defaults with application defaults $this->config = $this->config_group() + $this->config; } /** * Retrieves a fortune config group from the config file. One config group can * refer to another as its parent, which will be recursively loaded. * * @param STRING fortune config group; "default" if none given * @return ARRAY config settings */ public function config_group($group = 'default') { // Load the fortune config file $config_file = Kohana::config('fortune'); // Initialize the $config array $config = array('group' => (string)$group); // Recursively load requested config groups while(isset($config['group']) && isset($config_file->$config['group'])) { // Temporarily store config group name $group = $config['group']; unset($config['group']); // Add config group values, not overwriting existing keys $config += $config_file->$group; } // Get rid of possible stray config group names unset($config['group']); // Return the merged config group settings return $config; } /** * Randomly pick a fortune * * @return STRING fortune text */ public function getFortune() { // Stolen from: http://fortunes.cat-v.org/plan_9/ $fortunes = array('2 is always smaller than 3, even for large values of 2.', 'A penny saved is a political breakthrough.', 'Avoid reality at all costs.', 'Bad taste is timeless.'); $this->fortune = $fortunes[array_rand($fortunes, 1)]; } /** * Renders the fortune. * * @param MIXED string of the view to use, or a View object * @return STRING fortune output (HTML) */ public function render($view = NULL) { if($view === NULL) { // Use the view from config $view = $this->config['view']; } if(!$view instanceof View) { // Load the view file $view = View::factory($view); } $this->getFortune(); // Pass on the whole Fortune object return $view->set(get_object_vars($this))->set('page', $this)->render(); } /** * Renders the fortune. * * @return STRING fortune output (HTML) */ public function __toString() { return $this->render(); } } 

Save it as “fortune.php” in “/ modules / fortune / classes / kohana”. For the most part, the class looks like an uncomplicated part of the core of Kohana. We have two protected types: “config” and “fortune”. “Config” is intended for the configuration itself, and in the “fortune” there is one prediction of fate (we make an analogue of cookies with predictions), which will be displayed on the screen. Next, we have a “factory” method for implementing the corresponding pattern and a constructor that produces some manipulations with the “config” property.

The heart of the class is the getFortune method. I used to cheat here and instead of creating a model and retrieving data from the database, I simply used an array. A random element is taken from it and written into the “fortune” property.

Next we have the “render ()” method. It runs the “getFortune ()” method and visualizes the view. It, in turn, is called by the “__toString ()” method.

Create a new file with the following contents:

 <div style="width: 250px; height: 52px; vertical-align: middle; display: table-cell; text-align: center; border: 1px solid #CCCCCC; border-right-color: #666666; border-bottom-color: #666666;"> <p><?php echo $fortune;?></p> </div> 

Save it as “default.php” in “/modules/fortune/views/fortune/default.php”. As you can see, I, through “echo”, derive the $ fortune variable, which is a property of the protected type. This is because in the “render” method we passed all the properties to the mind, it's easier.

It remains to edit a couple of files. Open “/application/bootstrap.php” and find the section with the text “Kohana :: modules”. Replace it with this:

 Kohana::modules(array(// 'auth' => MODPATH.'auth', // Basic authentication // 'codebench' => MODPATH.'codebench', // Benchmarking tool 'database' => MODPATH.'database', // Database access // 'image' => MODPATH.'image', // Image manipulation // 'orm' => MODPATH.'orm', // Object Relationship Mapping // 'pagination' => MODPATH.'pagination', // Paging of results // 'userguide' => MODPATH.'userguide', // User guide and API documentation 'fortune' => MODPATH.'fortune', )); 

We added a module for predictions and included it in the framework. Now open the file “/application/views/pages/ko3.php” and add the line to the end:

 <?php echo Fortune::factory();?> 

Opening the browser “http: // localhost / mykohana3 / ko3 /”, you should see the prediction of fate below!

Part 9: Using Third-Party Libraries


First of all, you need to create the “vendors” folder in the “application” directory. In the “vendors” create a folder “Zend” (yes, with the capital “Z”). Next you need to download the latest version of Zend Framework (Minimal Package), at the time of publication it is 1.11.2. Open the archive and extract all of the “ZendFramework-1.11.2-minimal / library / Zend /” into “application / vendors / Zend”.

Open the file “application / bootstrap.php” and add the following above the line “echo Request :: getInstance ()”:

 $path = Kohana::find_file('vendors', 'Zend/Loader'); if($path) { ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . dirname(dirname($path))); require_once 'Zend/Loader/Autoloader.php'; Zend_Loader_Autoloader::getInstance(); } 

Open “application / views / pages / ko3.php” and paste at the very bottom:

 <?php $validator = new Zend_Validate_Isbn();?> <br />978-3-16-148410-0 <?php echo ($validator->isValid('978-3-16-148410-0')) ? 'is' : 'is not';?> valid. <br />9783161484100 <?php echo ($validator->isValid('9783161484100')) ? 'is' : 'is not';?> valid. 

Now at the address “http: // localhost / mykohana3 / ko3 ″ you should see the results of the two tests below.

Translator’s note: although the author of the cycle further promised to tell about forms, since June 2010 there have been no new articles. So this is the end of dating with Kohana 3.0.

Source: https://habr.com/ru/post/112338/


All Articles