$cache = app("cache");
app("cache"")
and expect a Cache\Repository
instance as result. If I pass the result of this call to a function that requires a Cache\Repository
as parameter, I will probably have a code inspection warning from IDE. Moreover, if I want proper autocompletion, I will have to add additional comment:
$cache = app("cache");
namespace App;
class MyApp extends Application
{
public function cacheRepository(): Repository
{
return $this->make(Repository::class);
}
}
TypeError
in case of a misconfiguration, and I have a type-hint which allows the IDE to recognize the return value. Bye-bye nasty comment lines and IDE warnings! I make a method per service, with type-hints, like dbConnection()
or viewFactory()
- works really well for me!bootstrap/app.php
, should reside in that custom class:namespace App;
class MyApp extends Application
{
public function __construct()
{
define('LARAVEL_START', microtime(true));
define("APP_ROOT", realpath(__DIR__ . "/../"));
parent::__construct(APP_ROOT);
$this->setUp();
}
private function setUp()
{
$this->singleton(
Contracts\Http\Kernel::class,
\App\Http\Kernel::class
);
}
}
bootstrap/app.php
becomes just this:return new \App\MyApp;
app()
function will also return an instance of MyApp from now on. However, it's @phpdoc says it returns \Illuminate\Foundation\Application
, so for better clarity, I also added my own accessor method:namespace App;
class MyApp extends Application
{
public static function app(): self
{
$ret = parent::getInstance();
return $ret;
}
}
MyApp::app()
. The IDE wil be aware of the return type due to the type-hint, so I get everything I want for clean and clear development.SPONSORS