D
D
Dmitry Cherednichenko2014-07-31 13:28:42
ORM
Dmitry Cherednichenko, 2014-07-31 13:28:42

What to move to the Kohana model?

Hello! Undertook to actively study PHP and Kohana. We decide to write a small CMS for an online store.
I worked hard and it turned out that all the models and me were empty for some reason .. The maximum that they contain is:

<?php defined('SYSPATH') or die('No direct script access.');

class Model_Product extends ORM {	
  
}

For some reason, I have everything in the controller .. probably, during the robot, I ignored the MVC logic:
<?php defined('SYSPATH') or die('No direct script access.');
 
class Controller_Products extends Controller_Common {
 
    public function action_index() {
    
        $content = View::factory('prodAll')
      ->bind('products', $products);
    
    // получаем данные из таблицы "products"
    $products = ORM::factory('product')->find_all();
    
    $this->template->title = 'Все товары'; 
    $this->template->description = 'Список всех товаров'; 
    $this->template->content = $content;
    
    // пагинация
    $count = ORM::factory('product')->count_all();
    $content->pagination = Pagination::factory(array('total_items' => $count));
    $products = ORM::factory('product')
      ->limit($content->pagination->items_per_page)
      ->offset($content->pagination->offset)
      ->find_all();
    }
  
  public function action_cart() {
  
    $content = View::factory('cartView');
    $this->template->title = 'Корзина покупок'; 
    $this->template->description = 'Список ваших товаров'; 
    $this->template->content = $content;
    $content->inCart = FALSE;
    $content->inCart = $this->session->get('product2');
  }
 
    public function action_product() {	
  
    //узнаем id материала
    $id = (int) Request::initial()->param('id');
    
    // получаем данные из таблицы "products"
    $product = ORM::factory('product', $id);
 
        $content = View::factory('prodView')
                        ->bind('product', $product);
    
    $this->template->title = $product->title;
    
        $this->template->content = $content;
    
    $content->inCart = FALSE;
    
    if(isset($_POST['Submit'])) {
      $clientName    = Arr::get($_POST, 'Name', '');
      $clientPhone = Arr::get($_POST, 'Phone', '');
      $clientAdress = Arr::get($_POST, 'Adress', '');
      $orderNumber = Arr::get($_POST, 'Number', '');
      
      $_POST = array(
        'name' => $product->name, 
        'number' => $orderNumber, 
        'url' => $product->url, 
        'client_name' => $clientName, 
        'client_phone' => $clientPhone,
        'client_adress' => $clientAdress
      );
        
        ORM::factory('order')
           ->values($_POST)
           ->save();
           
      Controller::redirect('main/ordered');
    }
    
    if(isset($_POST['InCart'])) {
      $this->session->set('product2', $product->name);
    }
    }    
} // Products

It seems to be like (as far as I understand) half of this controller should be in the model (connection to the database, for example).
I ask for help: how to correctly distribute the code between the controller and the model? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg Abrazhaev, 2014-07-31
@seyfer

Considering that the above code does not use the query builder from either the Database or the ORM (which is the same thing from the point of view of the query builder, practically), then there is nothing to move to the ORM model, which is inherited from the ORM.
The problem is deeper - it is in your understanding.
A model in business logic is not only ORM and other ways to access databases and storages, it is a complete description of business logic.
In fact, classes in Kohan can be used to store a hierarchy of simple classes, and the Model folder for simple and ORM models.
You need to move the logic to simple classes, which should be created for reasons of the entity that the class implements. Then there will be a hierarchy of classes, the interaction of objects, and in the controller just their call.
Once again, the main message - the model is not only access to the database. :)
In the database model, you can make custom sql queries or some kind of pre or post data processing.
Read about OOP and Patterns.
UPD.
Refactored the code. I would write something like this. You have everything confused. It's easier for me.

<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Products extends Controller_Base
{

    public function action_index()
    {
        // пагинация
        $count      = ORM::factory('product')->count_all();
        $pagination = Pagination::factory(array('total_items' => $count));
        $products   = ORM::factory('product')
                ->limit($pagination->items_per_page)
                ->offset($pagination->offset)
                ->find_all();

        $content = View::factory('prodAll')
                ->set('products', $products);

        //используется в шаблоне?
        $content->pagination = $pagination;

        $this->template->title       = 'Все товары';
        $this->template->description = 'Список всех товаров';
        $this->template->content     = $content;
    }

    public function action_cart()
    {

        $content = View::factory('cartView');

        $content->inCart = FALSE;
        $content->inCart = $this->session->get('product2');

        $this->template->title       = 'Корзина покупок';
        $this->template->description = 'Список ваших товаров';
        $this->template->content     = $content;
    }

    public function action_product()
    {
        //узнаем id материала
        $id   = $this->request->param('id');
        $post = $this->request->post();

        // получаем данные из таблицы "products"
        $product = ORM::factory('product', $id);
        $content = View::factory('prodView')
                ->set('product', $product);

        $this->template->title   = $product->title;
        $this->template->content = $content;
        $content->inCart         = FALSE;

        if (isset($post['Submit'])) {
            $this->processOrder($post, $product);

            Controller::redirect('main/ordered');
        }

        if (isset($post['InCart'])) {
            $this->session->set('product2', $product->name);
        }
    }

    /**
     * 
     * @param array $post
     * @param Model_Product $product
     */
    protected function processOrder($post, $product)
    {
        $clientName   = Arr::get($post, 'Name', '');
        $clientPhone  = Arr::get($post, 'Phone', '');
        $clientAdress = Arr::get($post, 'Adress', '');
        $orderNumber  = Arr::get($post, 'Number', '');

        $post = array(
            'name'          => $product->name,
            'number'        => $orderNumber,
            'url'           => $product->url,
            'client_name'   => $clientName,
            'client_phone'  => $clientPhone,
            'client_adress' => $clientAdress
        );

        ORM::factory('order')
                ->values($post)
                ->save();
    }

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question