Welcome Guest, Not a member yet? Register   Sign In
Calling library methods from a view
#1

[eluser]thody[/eluser]
Is it philosophically legit to call a library method directly from a view, or should it be done via a helper method? What are the advantages/disadvantages of each approach?
#2

[eluser]nhm tanveer hossain khan (hasan)[/eluser]
view should be as loosely coupled as possible.
if you put your library loading code on view, which means you are creating dependency on the specific library from the view. view is suppose to be as simple and neat as possible to render the output you expect.

i would rather prefer using helper method to do this job.
because later it would give me more flexibility to switch any library i want.

best wishes, Smile
#3

[eluser]thody[/eluser]
Actually, to be more specific, the situation I have in mind is for a global UI element, so the library would be loaded in autoload.php, and the only code in the view would be the fucntion call.

For example:
Code:
<ul>
&lt;? foreach ($this->sidebar->get_categories() as $cat) : ?&gt;
<li><$=cat->title; ?&gt;</li>
&lt;? endforeach; ?&gt;
</ul>
#4

[eluser]nhm tanveer hossain khan (hasan)[/eluser]
gotcha Big Grin
i don't think that is harming core philosophy so much since you are not writing the whole logic which was written under "get_categories" method. though you could load them under controller and send them over a variable. (which MVC suggests)
i am pretending this bunch of view code is used for creating modular component. which is not actually controller action dependent.

i have followed the following method in my code -
Code:
&lt;?= render_categories() ?&gt;

on helper you should have the following code -
Code:
function render_categories() {
  $this->load->view("common/categories", array(
    "categories" => $this->sidebar->get_categories()
  ));
}

On common/categories.php
Code:
<ul>
&lt;? foreach ($categories as $cat) : ?&gt;
<li><$=cat->title; ?&gt;</li>
&lt;? endforeach; ?&gt;
</ul>

it gives me chance to separate my logic and view with in the component scope. so later if i decide to change the logic in the category retrieval process or use separate library i don't need to touch the view.

best wishes Smile




Theme © iAndrew 2016 - Forum software by © MyBB