'Accessing an 'outer' class property within a class that was invoked in a callback in PHP
Apologies for the title, I wasn't sure of the best way to phrase this.
Essentially I'm trying replicate the absolute basics of Laravel's routing in a small personal application.
Below is the API I'm aiming for, however, I'm not sure how to access the namespace (api/v1) that's defined in the original Route::namespace call.
Route::namespace('api/v1')->group(function() {
Route::get('/posts/{id}', [PostController::class, 'show']);
Route::post('/posts', [PostController::class, 'store']);
});
So within the Route::get and Route::post methods, I need to somehow access that namespace value that was set via the outer call to Route::namespace. So Route::post('/posts') will end up registering an endpoint with the URI api/v1/posts.
Any pointers or guidance would much appreciated, Thanks.
Also here's the basic relevant parts of the Route class for reference.
class Route {
public function __construct(public string $namespace = '', private string $uri = '', private mixed $handle = null, private string $type = '')
{
return $this;
}
public static function namespace(string $namespace): Route
{
return new Route(namespace: $namespace);
}
public function group(Closure $callback): self
{
$callback($this);
return $this;
}
public static function get(string $uri, mixed $handle): Route
{
return new Route(uri: $uri, handle: $handle, type: 'get');
}
public static function post(string $uri, mixed $handle): Route
{
return new Route(uri: $uri, handle: $handle, type: 'post');
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
