I'm writting some kind of application in PHP, where developer can write his own plugins. As for now, to each plugin constructor object $project
is passed as argument (by reference of course). For example new plugin looks like this:
<?php
namespace Plugins;
class newPlugin {
private $project;
public function __construct(\Project $project) {
$this->project = $project;
}
public function Something() {
echo $this->project->template->name();
}
}
?>
I'm rewriting it, so every new plugin extends "standart" plugin. In that case, I can make a standart constructor which save passed $project
locally as $this->project
, and developer has less to write.
But then, every developer must remember, that there is something like $this->project...
For example:
<?php
namespace Plugins;
class newPlugin extends Plugin { // constructor is now in plugin class
public function Something() {
echo $this->project->template->name();
// where should the developer know from that $this->project exists?
}
}
?>
Can I make the notation easier somehow? Abbreviate $this->project
? I though about making a method project() in parent that will return $this->project
. In that case only project()->template->name();
can be used. But this is... Simply not the best I think.
I hope everything is clear in my question, if not please ask in comment. I searched for possible answers, but found nothing.
PHP "use" is great, but only for namespaces...
BTW, there are many, many other variables under $this->project available
, but the beginning $this->project
is always the same. For example: $this->project->template->name(); $this->project->router->url(); $this->project->page->title();
etc... This naming standart was imposed, so there is no way to change it.
But this is really annoying when you must write $this->project
every time you need a simple variable from somewhere.
Thanks for your help.
Here is sketched simple version of your project using __get()
overloading:
<?php
class Template
{
public function name()
{
return 'Template';
}
}
class Project
{
public $template;
public function __construct(Template $template)
{
$this->template = $template;
}
}
class Plugin
{
public $project;
public function __construct(Project $project)
{
$this->project = $project;
}
// here it is. It will be called, if $template property doesn't exist in this Plugin.
public function __get($val)
{
return $this->project->$val;
}
}
class newPlugin extends Plugin { // constructor is now in plugin class
public function Something() {
echo $this->template->name(); // using this we will call __get() method because $template property doesn't exist. It will be transformed to $this->project->template->name();
}
}
$template = new Template();
$project = new Project($template);
$plugin = new newPlugin($project);
$plugin->Something();
Output:
Template