Question

i want to instantiate a kohana controller function that gets the contents from a shopping basket, in another controller.

in other words, in one controller i have (in basket.php)

     public function action_index()
{
    $basket   = $this->basket;
    $contents = $basket->contents->find_all();

    $this->view->basket   = $basket;
    $this->view->contents = $contents;
}

and i want to call this function in other controller, sale.php because i want that the products already existent in the basket, to be marked somehow in the listing. i want to call this function in the controller sale.php, where the products are actually listed.

i have in sale.php

public function action_browse($id, $category_id = NULL) {

    $sale = Model::factory('sale')->active()->find($id);
    $basket_content = $this->user->get_basket($sale);


    if ( ! $sale->loaded())
    { 
        throw new Kohana_Request_Exception('Sale not found.');
    }

    if (isset($category_id))
    {
        $category = $sale->categories->find($category_id);
        if ( ! $category->loaded())
        {
            throw new Kohana_Request_Exception('Category not found.');
        }

        $products = $sale->products->category($category_id)->find_all();


        $this->view->category = $category;
    }
    else
    {
        $products = $sale->products->find_all();


    }

Thanks!

Was it helpful?

Solution

It's not advised to couple controllers to each other like this. This way you application would be very tied, and it would become a mess.

Try to decouple things as much as you can. You can do this for example by putting the logic in model where the controllers can fetch it.

In an ideal situation, you controller wouldn't be handling that much data at all, but it would mainly trying you models to your views.

The current preferred method would be to use view classes which pass the data from your models to your views. This way, a view would stand mostly on it's own, and has very little connection to the controller, which makes it easier to reuse your views.

Another feature of Kohana-3 that would come to mind is to use the Request class to execute an additional internal request, which would allow you to reuse the output of a controller in a decoupled way.

You would use it like this:

$response = Request::factory('basket/show')->execute()->response

Where response is that rendered output from the executed request, which you can output in your view. This method would be appropriate for a basket which gets rendered on every page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top