I’m quite new to PHP OOP and I’d like to merge both of these methods into a single one:
public function addRoute( string $httpMethod, string $route, callable|array $handler ): self
{
$this -> routes[$httpMethod][$route] = $handler;
return $this;
}
public function addRouteByAttribute( array $controllers )
{
foreach( $controllers as $controller ) {
$reflector = new \ReflectionClass( $controller );
foreach( $reflector -> getMethods() as $method ) {
$attributes = $method -> getAttributes( \Core\Attributes\Router::class, \ReflectionAttribute::IS_INSTANCEOF );
foreach( $attributes as $attribute ) {
$route = $attribute -> newInstance();
$this -> addRoute( $route -> httpMethod, $route -> route, [ $controller, $method -> getName() ] );
}
}
}
}
So basically the functionality of addRoute should be inside addRouteByAttribute.
How could I achieve this?
Thanks a lot!
CodePudding user response:
It is not good idea to create one big method which can do many things. It is violation of Single Responsibility principle of SOLID principles. So one method should have one goal.
So if you keep with two methods, your code will be simple, methods will be shorter and it will be easier to edit code and write unit tests.