如何通过artisan命令向服务提供商添加代码



我创建了一个用于创建Repository的Artisan命令。存储库文件和接口。当用户运行以下命令时,将生成这些文件。

php artisan make:repository RepositoryName

现在,下一步是在注册方法中向RepositoryServiceProvider添加绑定代码。如何将以下代码添加到该文件中?

$this->app->bind(
RepositoryNameInterface::class,
RepositoryName::class,
);

和一般情况下,如何添加自定义代码到类的方法在PHP?

您可以将存储库接口作为键,将存储库作为文件中数组中的值。

首先,添加use IlluminateFilesystemFilesystem;并在make:repository命令构造器中初始化它,如下所示:

protected $files;
public function __construct( Filesystem $files)
{
parent::__construct();
$this->files = $files;
}

让我们在make:repository命令中添加一个功能。

// Add a function in make:repository  command
public function writeToRepoCacheFile($repoName, $repoInterface)
{
//  Let's make sure cache folder exists
$cacheDirPath = base_path('bootstrap') . DIRECTORY_SEPARATOR . 'cache';
$this->files->ensureDirectoryExists($cacheDirPath);
// The full path we will be keeping the array of repos
$file = $cacheDirPath . DIRECTORY_SEPARATOR . 'repositories.php';
if (! is_writable(dirname($file))) {
throw new Exception('The '.dirname($file).' directory must be present and writable.');
}

// Merge with the previously added repo's if available
$repositories = [];
if ($this->files->exists($file)) {
$repositories = $this->files->getRequire($file);
}
$repositoryList = array_merge($repositories, [
$repoInterface => $repoName
]);

$this->files->replace($file, '<?php'. PHP_EOL . PHP_EOL .'return ' . var_export($repositoryList, true).';');
}

现在,无论何时创建一个新的repo,都应该调用writeToRepoCacheFile方法,并使用$repoName和$interface的参数及其各自的路径。该方法将简单地在bootstrap/cache文件夹中创建一个缓存文件,命名为repositories,并将您最近添加的repos作为一个数组添加到文件中,稍后将在我们的服务提供商中调用该数组以获取注册。

最后一个是绑定接口和我们的存储库。

public function bindTheRepos()
{
$repositories = base_path('bootstrap/cache/repositories.php');
if ($this->files->exists($repositories)) {
Collection::make($this->files->getRequire($repositories))
->map(function ($repo, $repoInterface) {

// Make sure the files exists
// Interface exists
$interfaceExists = $this->app['files']->exists(
$repoInterface.'.php'
);
// Repo exists
$repoExists = $this->app['files']->exists(
$repo.'.php'
);
if (
$interfaceExists &&
$repoExists
))) {
$this->app->bind($repoInterface, $repo);
} 
});
}
}

将上述函数添加到服务提供商中,并在服务提供商的register方法中调用该函数。

确保接口和存储库类路径匹配您的结构化路径。

这将动态地将新创建的存储库与其接口绑定。

相关内容

最新更新