'Access protected property when extending controller in OctoberCMS
I am struggling with extending a Plugin in OctoberCMS.
I need to access a protected property, so I wanted to create a new getter, that would return the value, but it always returns NULL
Here an example code of the controller (I cannot extend it here, as this is a 3rd party plugin):
class Records extends Controller
{
protected $some_value;
}
And this is how I implement it in the bootmethod of my Plugin:
Records::extend(function($controller) {
$controller->addDynamicMethod('myValue', function() use ($controller) {
return $controller->some_value;
});
});
But this does not work. When I dump the $controller I get sth like this:
MyNamespace\MyPlugin\Controllers\Records {#1616 ▼
#some_value: "1"
...
But when I want to return the value, it is null.
Solution 1:[1]
There is one hack that I used once. I was also facing the same issue
ref: https://tutorialmeta.com/octobercms/how-access-private-property-october-cms
// class
class Records extends Controller
{
protected $some_value;
// or private $some_value;
}
// in pugin
use Symfony\Component\VarDumper\Cloner\VarCloner;
Records::extend(function($controller) {
$controller->addDynamicMethod('myValue', function() use ($controller) {
$cloner = new VarCloner;
$cloned = $cloner->cloneVar($controller);
return $cloned->some_value;
});
});
It should do the trick and you can access variables.
please comment if any doubt
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hardik Satasiya |
