Question

I'm trying to understand the structure of MVC but I've stumbled upon a place.
How I should integrate global functions which using all pages in that structure.

To give an example;

I have a method which needed for all pages, Im displaying this in sidebar.

public function user_credit( $userid ){
  return $this->db->getSingleRow( "SELECT * FROM user_credit WHERE userid = $userid" );
}

Some pages dont need model file. I dont want to create model for all pages and add this method to all.

My Solutions;

1 ) I created a globalFunc.php and I saved in helpers folder.

globalFunc.php

// Extened model because I need db connection class GlobalFunc extends Model {

function __construct(){
     parent::__construct();
}
  public function user_credit( $userid ){
    return $this->db->getSingleRow( "SELECT * FROM user_credit WHERE userid = $userid" );}   

and I add loadHelper Method in base controller.

2 ) I saved globalFunc.php in Models folder. and I added loadCustomModel method in base Controller.

but this ways did not satisfy me. How should I follow a path?

Was it helpful?

Solution

First of all, do some more Reading on the Concept of MVC first. You'll get there.

To your Question: For Resources that have to be used by several other Resources, Components etc. etc. you usually use a Service. In some cases a Helper is a good Solution as well. Template Engines like Twig for Instance can use View Helpers for rendering. But those should be very abstract.

Services should be managed using Dependency Injection. You could have a DI Container which then provides instances of the services needed and can be used to manipulate them.

The Symfony2 Framework has a good DI Container Component that you can use. They also have a good Documentation Article on the DI Concept I think.

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