Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.xx] Add contextual attribute documentation #9808

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions container.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
- [Binding Basics](#binding-basics)
- [Binding Interfaces to Implementations](#binding-interfaces-to-implementations)
- [Contextual Binding](#contextual-binding)
- [Contextual Attributes](#contextual-attributes)
- [Binding Primitives](#binding-primitives)
- [Binding Typed Variadics](#binding-typed-variadics)
- [Tagging](#tagging)
Expand Down Expand Up @@ -225,6 +226,51 @@ Sometimes you may have two classes that utilize the same interface, but you wish
return Storage::disk('s3');
});

<a name="contextual-attributes"></a>
### Contextual Attributes

Alternatively, you can add contexual attributes directly to method parameters to tell the container which implementation to inject. For example, the `Illuminate\Container\Attributes\Storage` attribute allows you to specify the filesystem a controller requires:

use Illuminate\Container\Attributes\Storage;
use Illuminate\Contracts\Filesystem\Filesystem;

class PhotoController
{
public function __construct(#[Storage('local')] protected Filesystem $filesystem)
{
}
}

There are contextual attributes available for each of Laravel's built-in drivers: `Cache`, `Config`, `Database`, `Guard`, `Log` and `Storage`. You can also retrieve the currently authed user using the `Authed` contextual attribute:

use App\Models\User;
use Illuminate\Container\Attributes\Authed;

class UserController
{
public function __construct(#[Authed] protected ?User $user = null)
{
}
}

You can create your own contextual attributes by implementing the `Illuminate\Contracts\Container\ContextualAttribute` contract. The container will call your attribute's `resolve` method, which may contain the necessary logic to retrieve your implementation from the container:

use Illuminate\Contracts\Container\ContextualAttribute;

#[Attribute(Attribute::TARGET_PARAMETER)]
class Custom implements ContextualAttribute
{
public function __construct()
{
// Any properties needed to identify the implementation...
}

public static function resolve(self $attribute, Container $container)
{
// Return the implementation from the container...
}
}

<a name="binding-primitives"></a>
### Binding Primitives

Expand Down