📜 ⬆️ ⬇️

Introducing Kohana 3.0 - Part 4

Meet the fourth part of a series of articles on development with Kohana PHP V3 (KO3). The previous parts can be found under the tag " familiarity with kohana 3.0 ". This time it will be about working with models.

The model definition is taken from the Kohana 2.x documentation:
Models are classes designed to work with information transmitted or requested by the controller. For example, if you have a guest book, the controller queries the model for the last ten entries; the model returns them; the controller transmits this data to mind. The controller can also add new records using the model and update or delete existing ones.

In essence, a model is a data manipulator.

First of all, we need to determine what will be the data: XML tape, CSV, JSON, DB or something else? I will not torture you and say that this time we will work with a long-time friend of MySQL. Therefore, the next step is to set up a connection to the database.

Let's open the boot file (“application / bootstrap.php”), find the line “// 'database' => MODPATH.'database ', // Database access” and uncomment it. The whole block should now look like 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 )); 


Now save the file. We have just ordered the framework to load the database module, but it is not yet configured. Copy “database.php” from “modules / database / config /” to “application / config /”. Open the file “application / config / database.php” and edit it according to your settings. My looks like this:

 <?php defined('SYSPATH') OR die('No direct access allowed.'); return array ( 'default' => array ( 'type' => 'mysql', 'connection' => array( /** * The following options are available for MySQL: * * string hostname * integer port * string socket * string username * string password * boolean persistent * string database */ 'hostname' => 'localhost', 'username' => 'root', 'password' => FALSE, 'persistent' => FALSE, 'database' => 'mykohana3', ), 'table_prefix' => '', 'charset' => 'utf8', 'caching' => FALSE, 'profiling' => TRUE, ), 'alternate' => array( 'type' => 'pdo', 'connection' => array( /** * The following options are available for PDO: * * string dsn * string username * string password * boolean persistent * string identifier */ 'dsn' => 'mysql:host=localhost;dbname=mykohana3', 'username' => 'root', 'password' => FALSE, 'persistent' => FALSE, ), 'table_prefix' => '', 'charset' => 'utf8', 'caching' => FALSE, 'profiling' => TRUE, ), ); 


Save the file. For this series of articles I have created the database “mykohana3 ″, it is advisable for you to do the same. We will create a table in the database using the following SQL code:

 CREATE TABLE `posts` ( `id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT, `title` VARCHAR(255) DEFAULT NULL, `post` TEXT, PRIMARY KEY (`id`) ) ENGINE=INNODB DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC; 


Run it in your favorite MySQL client, I personally prefer SQLYog. Both in the database connection configuration and for the table I set the “utf8 ″ encoding. We will need this in the future.

Let's create a new “model” folder in “application / classes”. In it, create a new file and put the following there:

 <?php defined('SYSPATH') or die('No direct script access.'); class Model_Post extends Kohana_Model { /** * Get the last 10 posts * @return ARRAY */ public function getLastTenPosts() { $sql = 'SELECT *'."\n". 'FROM `posts`'."\n". 'ORDER BY `id` DESC'."\n". 'LIMIT 0, 10'; return $this->_db->query(Database::SELECT, $sql, FALSE) ->as_array(); } } 


Save it as “post.php” in “application / classes / model /”. Now we will sort the code line by line.

 $sql = 'SELECT *'."\n". 'FROM `posts`'."\n". 'ORDER BY `id` DESC'."\n". 'LIMIT 0, 10'; 


This is a basic MySQL query that selects up to ten records from the database, which are sorted by the 'id' field in descending order.

 return $this->_db->query(Database::SELECT, $sql, FALSE) ->as_array(); 


This returns an array with the result of the query. The “query” method in this example takes three parameters. The first is the type of the query, we have this “select”, so we are passing the constant “Database :: SELECT”. There are also three others: “Database :: INSERT”, “Database :: UPDATE” and “Database :: DELETE”. The “as_array ()” method returns an array with the results, so there is no need to do “while ($ row = mysql_fetch_array ())”.

Now that we have a method in our model, we can start using it. Open “ko3.php” in “/ application / classes / controller” and add the following code to the class:

 public function action_posts() { $posts = new Model_Post(); $ko3 = array(); $this->template->title = 'Kohana 3.0 Model Test'; $this->template->meta_keywords = 'PHP, Kohana, KO3, Framework, Model'; $this->template->meta_description = 'A test of of the KO3 framework Model'; $this->template->styles = array(); $this->template->scripts = array(); // Get the last 10 posts $ko3['posts'] = $posts->getLastTenPosts(); $this->template->content = View::factory('pages/posts', $ko3); } 


We just called the “getLastTenPosts ()” method from the model and placed the value returned by it into an array, which was then passed to our view. Speaking of views: open a new file and place there:

 <?php foreach($posts as $post):?> <h1><?php echo $post['title'];?></h1> <?php echo $post['post'];?> <hr /> <?php endforeach;?> 


Save it as “posts.php” in the “application / views / pages /” folder. This view enumerates the array transmitted by the controller and displays the records from the database. Although, stop, we have no articles in the database yet! Fix this with the following SQL queries:

 insert into `posts`(`id`,`title`,`post`) values (1,'Test Post','This is some sample text.'); insert into `posts`(`id`,`title`,`post`) values (2,'Another post','Some more text'); 


Now, going to “http: // localhost / mykohana3 / ko3 / posts”, you should see two entries.

Let's now implement the addition of new data to the database. Open our model ("application / classes / model / post.php") and add the following to the class:

 public function addPost($title, $post) { $sql = sprintf('INSERT INTO `posts`'."\n". 'SET `title` = %s,'."\n". ' `post` = %s', $this->_db->escape($title), $this->_db->escape($post)); $this->_db->query(Database::INSERT, $sql, FALSE); } 


Above is a fairly simple INSERT query, but what is “$ this -> _ db> escape ()”? This method will quote your string variables in quotes and clear them of garbage. Save it and go back to “posts.php” from “application / views / pages”. Replace its contents with this:

 <?php if(!empty($msg)):?> <?php echo $msg.'<br />';?> <?php endif;?> <?php foreach($posts as $post):?> <h1><?php echo $post['title'];?></h1> <?php echo $post['post'];?> <hr /> <?php endforeach;?> <form method="POST" action="<?php echo url::base();?>ko3/posts/"> <table> <tr> <td> Title </td> <td> <input type="text" name="title" style="border: 1px solid #000000;"/> </td> </tr> <tr> <td> Post </td> <td> <textarea cols="20" rows="5" name="post"></textarea> <input type="submit" name="submit" value="Submit"/> </td> </table> </form> 


Save the file and open the controller (“application / classes / controller / ko3.php”). Add a new method to it:

 private function _addPost($title, $post_content) { // Load model $post = new Model_Post(); // Check required fields if(empty($title)) { return(array('error' => 'Please enter a title.')); } elseif(empty($post_content)) { return(array('error' => 'Please enter a post.')); } // Add to DB $post->addPost($title, $post_content); return TRUE; } 


This code is an intermediate link between the “action_posts” and the model, it is used to directly save the record. Let's go back to the “action_posts” method and bring it to this form:

 public function action_posts() { // Load model $posts = new Model_Post(); // Setup view stuff $ko3 = array(); $this->template->title = 'Kohana 3.0 Model Test'; $this->template->meta_keywords = 'PHP, Kohana, KO3, Framework, Model'; $this->template->meta_description = 'A test of of the KO3 framework Model'; $this->template->styles = array(); $this->template->scripts = array(); $ko3['msg'] = ""; // Handle POST if($_POST) { $ret = $this->_addPost((isset($_POST['title']) ? $_POST['title'] : ""), (isset($_POST['post']) ? $_POST['post'] : "")); if(isset($ret['error'])) { $ko3['msg'] = $ret['error']; } else { $ko3['msg'] = 'Saved.'; } } // Get the last 10 posts $ko3['posts'] = $posts->getLastTenPosts(); // Display it. $this->template->content = View::factory('pages/posts', $ko3); } 


Save it and restart your browser. A scary form should appear at the bottom. Enter something and click "Send". If you have filled both fields, your entry should appear at the top along with the inscription “Saved”. Otherwise, an error message should appear.

Before I finish familiarizing myself with the models, I want to show how it was still possible to add a record to the database. There are several ways, but I will focus only on the so-called Query Builder. A mysql query in the addPost () method with it would look like this:

 public function addPost($title, $post) { DB::insert('posts', array('title','post')) ->values(array($title, $post)) ->execute(); } 


Query Builder is particularly useful in that it allows you to switch between different types of databases (from MySQL to Oracle, etc.)

I did not implement the update of the records in the model, so you can consider this as homework.

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


All Articles