Potential New Page Constructor Method

Hello.

I have a new page controller method I’d like to have evaluated. It works great for what I’m using it for…It seems to be a way of emulating the “if issset get function” so we can use the same view file for multiple models of data. Unless it has been done already, I pretty much evolved the same concept of active/inactive clients.

Is the following more efficient or will it cause problems?

So, if the argument id empty, use the view file as an index page. Otherwise, render the argued method in place of the index details. It also tells the user who manually types in an address that they got lost if they asked for a non-existent category.
This example shows how “product stats” can be sliced and diced on the same page (e.g. by customer, by quarter, by etc., etc., etc…

public function stats($type = '')
    {
        if ($type == ''){
			$this->load->model('mdl_prodstats');
			$data['items'] = $this->mdl_prodstats->buttons();
		} else{
			$function = 'by'.$type;
			$this->load->model('mdl_prodstats');
			if (method_exists('mdl_prodstats', $function)) {
				$data['items'] = $this->mdl_prodstats->$function();
			}
			else {$data['items'] = 'Dead End!  No data for this category.';}
		}
        
		$this->layout->buffer('content', 'products/stats', $data)->render();
    }

What I see as pros:

  • Very light view file (as low as 6 lines)
<div id="headerbar">
    <h1 class="headerbar-title">Product Stats</h1>
</div>

<div class="container" >

	<?=$items;?>

</div>
  • Dont have to write multiple contollers with repetitive lines of code
  • If a new category of the type of data needs modeled and displayed, all you have to do is create the model method and update the Nav. (writing code on Two files vs Four)
    – Makes working with the CMV framework a lot smoother when adding several pages for the same class

Thoughts?

There is merit in a “supercontroller approach”. As you have shown in your example, you can trim code down substantially.

On the other hand, what you gain with less code might be eroded by increased complexity inside your controllers. An overly large controller class will be frowned upon by some coders (and lint programs, which complain if your code is too large).

The underlying MVC framework (CI in this case) does allow you to share view segments, so creating a partial view for (say, for example) display of a table needs only happen once, and all calling views use the shared partials.

A superclass approach is useful if the code is managed by a one of two developers, with tight control of changes. In a more open environment, as displayed by many open source projects, having many pending changes inside a large code file might lead to code conflicts (with git).

Ultimately, the choice if going with a superclass approach, or using many smaller, classes is a question of the application architecture of the project.