Jump to content

PHP5 - Creating a single instance for an entire application?


Perad

Recommended Posts

Hi,

 

I am trying to write a small MVC framework. I am having a little trouble setting something up. I want to have a single instance for the entire application.

 

For example.

 

The instance would contain the following.

$this->db

$this->session

$this->validation

 

These should be accessible to all classes should they try to access them.

 

I have heard about magic __get() __set() methods but don't quite understand how they work or if they would help. Does anyone know how I can achieve this?

 

If __get() __set() methods can be used could someone briefly explain how.

 

Thanks

Thanks, that sounds like it would work. So am I right in thinking that I would do something like this...

 

class instance {

}

 

Then something like this.

 

class controller {
  public function __construct($instance) {
    $this->i = $instance;
  }
}

 

class c extends controller {
  public function __construct() {
    $this->i->db = $this->load->library('db');
    $this->i->auth = $this->load->library('db');
    $this->i->session = $this->load->library('db');
  }
}

 

This actually wouldn't require much modification to adapt what I have at the moment. Have I interpreted this correctly?

Everything you specify in your controller (db, auth, session) is actually just a model and these may be present in the controller. I actually do not recommend adding your db directly into your controllers as your controller does not need to know that your application uses a database nor that it uses sessions. You can hide these behind a new model layer for example:

 

$user = UserRepository::findByUsername(..);

 

Uses a database to find the username but it actually does not know if this database is mysql, a flat file or sqlite or something..

 

Same applies for auth:

 

AuthService::logon($this->getRequest());

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.