I'm trying to create small PHP framework for my own needs (and likes). However there are questions for which I may need advice of more wise and experienced people before things became too complicated - so I moved it to github from private repo.
Currently I'm curious about organizing imports of modules better. I use the special object, "context" - to hold links to all necessary modules - data access objects, utils etc. I use lazy initialization here, so that when field of this object is required, it is provided by the getter of the same name.
It looks like:
class ProtoContext {
function __get($name) {
$methodName = 'get' . ucfirst($name);
if (!method_exists($this, $methodName)) {
throw new Exception("No property '$name' in Context!");
}
$res = $this->$methodName();
if (is_object($res)) {
$res->ctx = $this;
}
$this->$name = $res;
return $res;
}
protected function getElems() {
return Elems::$elems;
}
protected function getUtil() {
module('sys/Util');
return new Util();
}
}
main Context class is inherited from this ProtoContext, though it is not significant now. With the grow of application context may look like this:
module('sys/ProtoContext');
class Context extends ProtoContext {
protected function getAuth() {
module('MyAuth');
return new MyAuth();
}
protected function getUsersDao() {
module('dao/MysqlDao');
return new MysqlDao('users');
}
protected function getRolesDao() {
module('dao/MysqlDao');
return new MysqlDao('roles');
}
/*
* 5-10 more similar methods 'getSomethingDao'
* each including MysqlDao via method 'module'
*/
protected function getLinksCViewDao() {
module('dao/MysqlDao');
return new MysqlDao('linksc_view');
}
}
There is no problem that module
method may be called several times, include is performed once only. However it looks annoying that inclusion of MysqlDao is mentioned so many times. On the other hand if I pull it above the class (like import of ProtoContext) it will be imported even if I need it not. For example when addressing $ctx->auth field (which will call getAuth method).
I wonder, whether here is comfortable workaround which will preserve lazy load and lazy initialization - and at the same time will allow to get rid of extra imports?
module
method if we already have lazy loading trough autoloading? It looks to me you're doing something that's been done before (and much better). \$\endgroup\$ – N.B. Aug 5 '13 at 13:21