如何在 Laravel 中创建 Artisan 命令来管理数据库记录

但是,您仍然需要实施一种方法,让用户在链接表中插入新条目。

为了限制本系列的范围,同时使应用程序完全功能,您将设置Artisan命令来创建和删除数据库中的链接.Artisan是与Laravel一起提供的命令行工具,提供一系列实用程序来加快开发过程,从生成锅板代码到删除和重新创建应用程序的数据库。

使用命令行界面来管理应用程序可以替代 Web 表单和安全区域,因为它需要用户登录到服务器以执行此类命令,而不是通过浏览器进行身份验证。

手工命令通常用于执行应用程序任务,这些任务应该在背景中运行,无论是手动或通过Crontab等编程机制自动执行,也可以用于简化需要动态配置的新应用程序功能的原型,这取决于授权用户的输入。

要开始,使用make:command辅助程序创建一个新的艺术家命令:

1docker-compose exec app php artisan make:command LinkNew
1[secondary_label Output]
2Console command created successfully.

这将创建一个名为LinkNew.php的文件,位于app/Console/Commands目录中。在这个类中,从Illuminate\Console\Command母类扩展到Illuminate\Console\Command,你需要实施一个处理方法,当这个命令被调用时执行。为了定义命令的签名,你将$签名保护的属性设置为link:new

使用您所选择的文本或代码编辑器打开新文件. 在这里,使用‘nano’:

1nano app/Console/Commands/LinkNew.php

在)以获取链接的URL。

1$url = $this->ask('Link URL:');

然后,您将使用filter_var函数来验证从用户获得的输入是有效的 URL. 如果链接无效,您将显示错误并以状态代码1离开应用程序,这意味着应用程序在错误中退出。

1if (!filter_var($url, FILTER_VALIDATE_URL)) {
2            $this->error("Invalid URL. Exiting...");
3            return 1;
4        }

如果链接有效,您将继续使用与之前相同的方法请求链接描述。

1$description = $this->ask('Link Description:');

然后,您将使用 confirm 帮助程序请求最后确认所有数据是否正确。如果用户确认,链接最终被插入数据库中。您将使用在本系列中创建的 Link Eloquent 模型与数据库进行交互。

 1$this->info("New Link:");
 2        $this->info($url . ' - ' . $description);
 3
 4        if ($this->confirm('Is this information correct?')) {
 5            $link = new Link();
 6            $link->url = $url;
 7            $link->description = $description;
 8            $link->save();
 9
10            $this->info("Saved.");
11        }

应用程序以)。

1return 0;

下面的代码包含了这些步骤的完整实现,您可以在LinkNew类中的当前内容替换为:

 1[label app/Console/Commands/LinkNew.php]
 2<?php
 3
 4namespace App\Console\Commands;
 5
 6use App\Models\Link;
 7use Illuminate\Console\Command;
 8use Illuminate\Support\Facades\DB;
 9
10class LinkNew extends Command
11{
12    /**
13     * The name and signature of the console command.
14     *
15     * @var string
16     */
17    protected $signature = 'link:new';
18
19    /**
20     * The console command description.
21     *
22     * @var string
23     */
24    protected $description = 'Create a New Link';
25
26    /**
27     * Create a new command instance.
28     *
29     * @return void
30     */
31    public function __construct()
32    {
33        parent::__construct();
34    }
35
36    /**
37     * Execute the console command.
38     *
39     * @return int
40     */
41    public function handle()
42    {
43        $url = $this->ask('Link URL:');
44
45        if (!filter_var($url, FILTER_VALIDATE_URL)) {
46            $this->error("Invalid URL. Exiting...");
47            return 1;
48        }
49
50        $description = $this->ask('Link Description:');
51
52        $this->info("New Link:");
53        $this->info($url . ' - ' . $description);
54
55        if ($this->confirm('Is this information correct?')) {
56            $link = new Link();
57            $link->url = $url;
58            $link->description = $description;
59            $link->save();
60
61            $this->info("Saved.");
62        }
63
64        return 0;
65    }
66}

保存并关闭文件,当你完成。

要执行命令并在数据库中插入新链接,运行:

1docker-compose exec app php artisan link:new
 1[secondary_label Output]
 2 Link URL::
 3 > https://digitalocean.com/community
 4
 5 Link Description::
 6 > DigitalOcean Community
 7
 8New Link:
 9https://digitalocean.com/community - DigitalOcean Community
10
11 Is this information correct? (yes/no) [no]:
12 > yes
13
14Saved.

您可以自由地添加一些更多的链接,如果你愿意。

列表 链接

接下来,您需要创建一个新的艺术家命令,以显示所有链接的列表。您可以将其称为link:list

1docker-compose exec app php artisan make:command LinkList

使用您所选择的文本或代码编辑器打开命令类:

1nano app/Console/Commands/LinkList.php

在这个命令的)。 为了在命令行中显示结果,您可以使用 [table](https://laravel.com/docs/8.x/artisan tables)输出助手:

1$headers = [ 'id', 'url', 'description' ];
2        $links = Link::all(['id', 'url', 'description'])->toArray();
3        $this->table($headers, $links);
4
5        return 0;

下面的代码包含了link:list命令的完整执行,请将您的LinkList.php文件中的内容替换为:

 1[label app/Console/Commands/LinkList.php]
 2<?php
 3
 4namespace App\Console\Commands;
 5
 6use App\Models\Link;
 7use Illuminate\Console\Command;
 8
 9class LinkList extends Command
10{
11    /**
12     * The name and signature of the console command.
13     *
14     * @var string
15     */
16    protected $signature = 'link:list';
17
18    /**
19     * The console command description.
20     *
21     * @var string
22     */
23    protected $description = 'List links saved in the database';
24
25    /**
26     * Create a new command instance.
27     *
28     * @return void
29     */
30    public function __construct()
31    {
32        parent::__construct();
33    }
34
35    /**
36     * Execute the console command.
37     *
38     * @return int
39     */
40    public function handle()
41    {
42        $headers = [ 'id', 'url', 'description' ];
43        $links = Link::all(['id', 'url', 'description'])->toArray();
44        $this->table($headers, $links);
45
46        return 0;
47    }
48}

保存并关闭文件,当你完成。

要运行此命令并显示已经插入到链接表中的所有链接的列表,请运行:

1docker-compose exec app php artisan link:list
1[secondary_label Output]
2+----+------------------------------------+--------------+
3| id | url                                | description  |
4+----+------------------------------------+--------------+
5| 1  | https://digitalocean.com/community | DO Community |
6| 2  | https://laravel.com                | Laravel      |
7+----+------------------------------------+--------------+

删除链接

最后,您将创建一个命令以删除**链接:

1docker-compose exec app php artisan make:command LinkDelete
1[secondary_label Output]
2Console command created successfully.

使用您选择的文本或代码编辑器打开新文件:

1nano app/Console/Commands/LinkDelete.php

要知道哪些链接必须删除,您需要要求用户在调用该命令时提供一个额外的论点:链接的ID。 这也设置在)以及哪些论点,强制性或不强制性,应该提供:

1protected $signature = 'link:delete {link_id}';

此命令的处理方法将执行几个不同的命令. 首先,您将获得命令呼叫中应该提供的链接 ID。

1$link_id = $this->argument('link_id');

然后,您将从数据库中获取引用链接,使用通过您的链接模型可用的 Eloquent 方法查找

1$link = Link::find($link_id);

查找方法找不到具有该ID的数据库记录时,它会返回null。你会检查它是否是包含在$link变量中的当前值,然后返回错误。

1if ($link === null) {
2            $this->error("Invalid or non-existent link ID.");
3            return 1;
4        }

當「$link」不是無效時,命令會繼續執行,然後使用「確認」助手來要求使用者確認。

1if ($this->confirm('Are you sure you want to delete this link? ' . $link->url)) {
2    // deletes link
3}

当用户通过键入和键入ENTER来确认操作时,您将从链接 Eloquent 模型中调用删除方法来从数据库中删除指定的链接。

1$link->delete();
2            $this->info("Link deleted.");

下面的代码包含了list:delete命令的完整实现,请用以下代替LinkDelete.php文件中的内容:

 1[label app/Console/Commands/LinkDelete.php]
 2<?php
 3
 4namespace App\Console\Commands;
 5
 6use App\Models\Link;
 7use Illuminate\Console\Command;
 8use Illuminate\Support\Facades\DB;
 9
10class LinkDelete extends Command
11{
12    /**
13     * The name and signature of the console command.
14     *
15     * @var string
16     */
17    protected $signature = 'link:delete {link_id}';
18
19    /**
20     * The console command description.
21     *
22     * @var string
23     */
24    protected $description = 'Deletes a link from the database.';
25
26    /**
27     * Create a new command instance.
28     *
29     * @return void
30     */
31    public function __construct()
32    {
33        parent::__construct();
34    }
35
36    /**
37     * Execute the console command.
38     *
39     * @return int
40     */
41    public function handle()
42    {
43        $link_id = $this->argument('link_id');
44        $link = Link::find($link_id);
45
46        if ($link === null) {
47            $this->error("Invalid or non-existent link ID.");
48            return 1;
49        }
50
51        if ($this->confirm('Are you sure you want to delete this link? ' . $link->url)) {
52            $link->delete();
53            $this->info("Link deleted.");
54        }
55
56        return 0;
57    }
58}

保存并关闭文件,当你完成。

现在,当你想从链接表中删除一个链接时,你需要先获得链接的ID,如前面所示,artisan link:list

1docker-compose exec app php artisan link:delete LINK_ID
1[secondary_label Output]
2
3Are you sure you want to delete this link? https://laravel.com (yes/no) [no]:
4 > yes
5
6Link deleted.

您现在可以插入、列出和删除应用程序数据库中的链接,使用从命令行界面执行的 Artisan 命令. 在本系列的下一部分中,您将使用 Blade 模板和 Bulma CSS 框架设置应用程序的前端。

Published At
Categories with 技术
comments powered by Disqus