I have a problem here that I have been thinking about for the last few days. In a php application, to do something with an object, you need:
- identify him
- run a function with it like this: (with autoload and a registry object)
- $ registry-> obj = new mathClass ($ var1, $ var2); // creates an object where $ var1 contains the database object and $ var2 has the value 1, for example
- $ registry-> obj-> Calculate ('value'); // selects rows of products and returns their total value. That way, at any time in the script, I can just run the calculation function (or some other function) that I defined in advance.
Imagine a web application that has hundreds of classes that may or may not be required for this particular page load, but can only be defined at the beginning of the application. The desired solution is that I just run
$obj->calculate('price');
without creating an object for example
mathclass::calculate('price');
then it automatically loads the math class without requiring major overhead, the problem is that I can no longer give math any variables at the beginning
($var1,$var2).
I want to be able to pseudo-create an object without any autoload of the class, so as not to add overhead, but that the object creates itself with variables, but only when I really need to do something with it.
, php , , ?
Lazy-loading? ?
, , , .
2015: :
class Service {
private $cb, $instance;
public function __construct($cb){
$this->cb = $cb;
}
public function __invoke() {
if(!$this->instance){
$this->instance = call_user_func($this->cb);
}
return $this->instance;
}
}
set_include_path(__DIR__.'/vendor'. PATH_SEPARATOR .get_include_path());
spl_autoload_register(function($c){
include preg_replace('#\\\|_(?!.+\\\)#','/',$c).'.php';
});
$service['db'] = new Service(function(){
return new Database('sqlite::filename.sqlite');
});
$service['config'] = function() use(&$service){
return new Config($service['db']());
};
$service['math'] = function() use(&$service){
return new Math($service['config']());
};
$service['math']()->calculate('price');