Ok folks, this is what I'm trying to accomplish here.
I want to call a method each time that another method is called, like a middle man.
I'm aware of these magic methods: __call($method, $args) and __callStatic($method, $args) and how they kick in when a method from a class is not accessible or does not exist if it's called.
Ok. Let's say I have this class and all its methods are public (accessible), no problem at all so far but I need to call the middleware() method within all other methods that I require:
class A {
public function test()
{
$this->middleware();
echo "Test method\n";
}
public function middleware()
{
echo "Middleware method\n";
}
}
// [some code]
$foo = new A();
$foo->test(); // Output: Middleware method
// Test method
Now, I'd like to call a method, from this class or another inherited one, before $foo->test() body is called.
I know that I can achieve this if I do the next:
class A {
private function test()
{
echo "Test method\n";
}
private function middleware()
{
echo "Middleware method\n";
}
public function __call( $method, $args )
{
$this->middleware();
$this->$method(...$args);
}
}
// [some code]
$foo = new A();
$foo->test(); // Output: Middleware method
// Test method
This way can lead to "force" any developer to write all methods as private or protected. No bueno.
Now, what about if there is a trait (preferably) or class that makes just the requested methods non-accessible?. Something like:
trait ChangeVisibility {
// ReflectionClass, ReflectionObject?...
// __constructor(){...}?....
// Another technique?...
// ...
}
trait Middleware {
public function __call( $method, $args )
{
$this->middleware();
$this->$method(...$args);
}
}
Then use these traits in a class like this:
class A {
use ChangeVisibility, Middleware;
public function test()
{
echo "Test method\n";
}
public function middleware()
{
echo "Middleware method\n";
}
}
// [some code]
$foo = new A();
$foo->test(); // Output?: Middleware method
// Test method
Something worth mentioning is that I don't want to follow the container service technique, I hope if I could achieve this without it, just plain classes and traits or another way would be more simple, direct, and maybe "elegant".
This is my limit and I'm in the burndown zone now, that's why I'm reaching out to you.
Thanks to everyone.