Skip to content

Proposal: Context Class #47

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

Open
rayblair06 opened this issue Sep 6, 2024 · 2 comments
Open

Proposal: Context Class #47

rayblair06 opened this issue Sep 6, 2024 · 2 comments

Comments

@rayblair06
Copy link
Contributor

rayblair06 commented Sep 6, 2024

Opening this up for discussion: what do you all think about the idea of introducing class instantiation directly into the context, like $context->get(Foo::class, 'bar')? I think this could be a really cool addition, but I also realize we might be edging toward implementing a service container. Not sure if that's necessarily a bad thing—thoughts?

I have some code below, but feel free to pull my branch here for a demo.

$app = new Dumbo();

class SimpleMessage
{
    public function __construct(
        public string $messageOne,
        public string $messageTwo
    ) {}
    
    public function getMessage(): string
    {
        return "{$this->messageOne} {$this->messageTwo}";
    }
}

class InjectedMessage
{
    public function __construct(public SimpleMessage $message)
    {}
    
    public function getInjectedMessage(): string
    {
        return "{$this->message->getMessage()} This is an injected class.";
    }
}


// Context middleware for all routes
$app->use(function ($context, $next) {
    $context->set(SimpleMessage::class, "Hello", "Dumbo!");
    $context->set(
        InjectedMessage::class,
        new SimpleMessage('Hello', 'Dumbo!')
    );

    return $next($context);
});

$app->get("/", function ($context) {
    $messageClass = $context->get(SimpleMessage::class);
    $message = $messageClass->getMessage();

    return $context->json([
        "message" => $message,
    ]);
});

$app->get("/injection", function ($context) {
    $injectedClass = $context->get(InjectedMessage::class);
    $message = $injectedClass->getInjectedMessage();

    return $context->json([
        "message" => $message,
    ]);
});
@josephajibodu
Copy link
Contributor

Looks like a cool addition though.

Are there use cases when this might prove very useful for instantiating the class the normal way?

@notrab
Copy link
Owner

notrab commented Oct 18, 2024

I haven't forgot this 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants