Skip to content

Instantly share code, notes, and snippets.

@lighth7015
Last active January 8, 2020 01:12
Show Gist options
  • Save lighth7015/e1c7eccf06277d41fba6fd7fe23b1096 to your computer and use it in GitHub Desktop.
Save lighth7015/e1c7eccf06277d41fba6fd7fe23b1096 to your computer and use it in GitHub Desktop.
Laravel Reflection

This is a simply thrown-together gist to demonstrate an issue I'm having with laravel's service container; for somee reason I'm unable to resolve() classes with mixed typed and numbered constructor arguments. Any idea why this is happening for me?

<?php
require_once 'vendor/autoload.php';
use Illuminate\Support\Arr;
/**
* Demo with some reflection, I'm working on this for a project and need
* this working or at least a viable workaround very soon, thanks!
*/
class SlackRegistration { }
class SlackMessage {
public function __construct( $instance, int $notifiable ) {
dd( func_get_args(), $notifiable, $instance );
}
}
class Registered {
private function reduce(): Closure {
return function( array $parameters, ReflectionParameter $parameter ) {
array_push( $parameters, $parameter->getName());
return $parameters;
};
}
private function reflect(): array {
$frame = Arr::get(debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, 2), 0);
$method = new ReflectionMethod( $this, Arr::Get( $frame, 'function' ));
$prototype = array_reduce( $method->getParameters(), $this->reduce(), array());
$named = Arr::get( $frame, 'args' );
return array_merge( array_slice( $named, count( $named ) - 1),
array_combine( $prototype, array_slice( $named, 0, count( $named ) - 1)));
}
/*
* I can't provide numbered arguments that match numbered arguments
* in the object I'm creating's constructor?
*/
private function createInstance( string $className, $notifiable ) {
dump( $this->reflect());
return resolve( $className, [ 213, 123 ]);
}
/**
* Deliver mail to new members.
*
* @param object $event
* @return void
*/
public function handle($event) {
$this->createInstance( SlackMessage::class, $event->account, resolve( SlackRegistration::class ));
}
}
$registered = resolve(Registered::class);
$registered->handle(new class {
public int $account = 0;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment