国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

ホームページ バックエンド開発 PHPチュートリアル Laravel で動(dòng)的で保守可能なメニューを構(gòu)築する

Laravel で動(dòng)的で保守可能なメニューを構(gòu)築する

Dec 14, 2024 pm 10:28 PM

Laravel アプリケーションが成長するにつれて、特にロールベースのアクセス制御などの動(dòng)的要素の場合、ナビゲーション メニューの管理が困難になることがあります。このブログ投稿では、メニュー ビルダー システムを使用してメニューを簡素化し、構(gòu)造化し、メンテナンス、拡張、拡張を容易にする方法について説明します。


問題

多くの Laravel プロジェクトでは、Blade テンプレートは條件文を使用してメニューの可視性を処理します。

@can('viewAdmin')
    <a href="{{ route('administration.index') }}">
        {{ __('Administration') }}
    </a>
@endcan

このアプローチは単純なアプリケーションでは機(jī)能しますが、メニューの數(shù)が増えると亂雑になり管理できなくなります。


解決策

メニュー ビルダー システム は、メニュー ロジックを再利用可能なクラスにカプセル化し、以下を改善します。

  1. 保守性: 一元化されたメニュー定義。
  2. スケーラビリティ: 役割または権限に基づいてメニューを動(dòng)的に生成します。
  3. 再利用性: ビュー間でメニューを共有します。

私の仕事を後援することで、開発者コミュニティに力を與えるという私の使命をサポートしてください。あなたの貢獻(xiàn)は、貴重なツール、洞察、リソースを構(gòu)築して共有するのに役立ちます。詳細(xì)については、こちらをご覧ください。


段階的な実裝

1. viewAdmin のゲートを定義する

管理メニューへのアクセスを制御するには、AuthServiceProvider で viewAdmin ゲートを定義します。

use Illuminate\Support\Facades\Gate;
use App\Models\User;

class AuthServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->registerPolicies();

        Gate::define('viewAdmin', function (User $user) {
            return $user->hasRole('admin'); // Replace with your app's role-checking logic
        });
    }
}

2. MenuItem クラスを作成します

MenuItem クラスは、ラベル、URL、アイコン、可視性などのメニュー項(xiàng)目のすべての屬性を定義します。

<?php

namespace App\Actions\Builder;

use CleaniqueCoders\Traitify\Contracts\Builder;
use InvalidArgumentException;

class MenuItem implements Builder
{
    private string $label;
    private string $url;
    private string $target = '_self';
    private array $attributes = [];
    private array $children = [];
    private string $icon = 'o-squares-2x2';
    private ?string $description = null;
    private ?string $tooltip = null;
    private $visible = true;
    private array $output = [];

    public function setLabel(string $label): self
    {
        $this->label = $label;

        return $this;
    }

    public function setUrl(string $url): self
    {
        $this->url = $url;

        return $this;
    }

    public function setTarget(string $target): self
    {
        $this->target = $target;

        return $this;
    }

    public function addAttribute(string $key, string $value): self
    {
        $this->attributes[$key] = $value;

        return $this;
    }

    public function addChild(MenuItem $child): self
    {
        $this->children[] = $child;

        return $this;
    }

    public function setIcon(string $icon): self
    {
        $this->icon = $icon;

        return $this;
    }

    public function setDescription(string $description): self
    {
        $this->description = $description;

        return $this;
    }

    public function setTooltip(string $tooltip): self
    {
        $this->tooltip = $tooltip;

        return $this;
    }

    public function setVisible($visible): self
    {
        if (! is_bool($visible) && ! is_callable($visible)) {
            throw new InvalidArgumentException('The visible property must be a boolean or a callable.');
        }

        $this->visible = $visible;

        return $this;
    }

    public function isVisible(): bool
    {
        return is_callable($this->visible) ? call_user_func($this->visible) : $this->visible;
    }

    public function build(): self
    {
        $this->output = [
            'label' => $this->label,
            'url' => $this->url,
            'target' => $this->target,
            'attributes' => $this->attributes,
            'icon' => $this->icon,
            'description' => $this->description,
            'tooltip' => $this->tooltip,
            'children' => array_filter(
                array_map(fn (MenuItem $child) => $child->build()->toArray(), $this->children),
                fn (array $child) => ! empty($child) 
            ),
        ];

        return $this;
    }

    public function toArray(): array
    {
        return $this->output;
    }

    public function toJson(int $options = 0): string
    {
        return json_encode($this->toArray(), $options, 512);
    }
}


3.メニュービルダーを作成します

メニュー ビルダーはメニューを動(dòng)的に解決して構(gòu)築します。

namespace App\Actions\Builder;

class Menu
{
    public static function make()
    {
        return new self;
    }

    public function build(string $builder)
    {
        $class = match ($builder) {
            'navbar' => Navbar::class,
            'sidebar' => Sidebar::class,
            'administration' => Administration::class,
            default => Navbar::class,
        };

        $builder = new $class;
        return $builder->build();
    }
}

ヘルパー関數(shù)を使用してメニューにアクセスします:

<?php

use App\Actions\Builder\Menu;

if (! function_exists('menu')) {
    function menu(string $builder)
    {
        return Menu::make()->build($builder)->menus();
    }
}

4.管理メニュー

Administration クラスで管理固有のメニュー項(xiàng)目を定義します。

<?php

namespace App\Actions\Builder\Menu;

use App\Actions\Builder\MenuItem;
use CleaniqueCoders\Traitify\Contracts\Builder;
use CleaniqueCoders\Traitify\Contracts\Menu;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Gate;

class Administration implements Builder, Menu
{
    private Collection $menus;

    public function menus(): Collection
    {
        return $this->menus;
    }

    public function build(): self
    {
        $this->menus = collect([
            (new MenuItem)
                ->setLabel(__('Issues'))
                ->setUrl(url(config('telescope.path')))
                ->setTarget('_blank')
                ->setVisible(fn () => Gate::allows('viewTelescope'))
                ->setTooltip(__('View Telescope issues'))
                ->setDescription(__('Access application issues using Laravel Telescope'))
                ->setIcon('o-bug'), // Heroicon outline for a bug

            (new MenuItem)
                ->setLabel(__('Queues'))
                ->setUrl(url(config('horizon.path')))
                ->setTarget('_blank')
                ->setVisible(fn () => Gate::allows('viewHorizon'))
                ->setTooltip(__('Manage queues'))
                ->setDescription(__('Access Laravel Horizon to monitor and manage queues'))
                ->setIcon('o-cog'), // Heroicon outline for settings/tasks

            (new MenuItem)
                ->setLabel(__('Access Control'))
                ->setUrl(route('security.access-control.index'))
                ->setVisible(fn () => Gate::allows('viewAccessControl'))
                ->setTooltip(__('Manage access control'))
                ->setDescription(__('Define and manage access control rules'))
                ->setIcon('o-lock-closed'), 

            (new MenuItem)
                ->setLabel(__('Users'))
                ->setUrl(route('security.users.index'))
                ->setVisible(fn () => Gate::allows('viewUser'))
                ->setTooltip(__('Manage users'))
                ->setDescription(__('View and manage user accounts'))
                ->setIcon('o-user-group'), 

            (new MenuItem)
                ->setLabel(__('Audit Trail'))
                ->setUrl(route('security.audit-trail.index'))
                ->setVisible(fn () => Gate::allows('viewAudit'))
                ->setTooltip(__('View audit trails'))
                ->setDescription(__('Audit logs for security and activity tracking'))
                ->setIcon('o-document-text'), 
        ])->reject(fn (MenuItem $menu) => ! $menu->isVisible())
            ->map(fn (MenuItem $menu) => $menu->build()->toArray());

        return $this;
    }
}

5.ルートを定義する

管理ページに次のルート構(gòu)成を追加します:

<?php

use Illuminate\Support\Facades\Route;

Route::middleware(['auth:sanctum', 'verified', 'can:viewAdmin'])
    ->as('administration.')
    ->prefix('administration')
    ->group(function () {

        Route::view('/', 'administration.index')->name('index');

    });

6. Blade テンプレートでの使用法

ナビゲーション メニュー (navigation-menu.blade.php):

@can('viewAdmin')
    <a href="{{ route('administration.index') }}">
        <x-icon name="o-computer-desktop" />
        {{ __('Administration') }}
    </a>
@endcan

管理メニュー (administration/index.blade.php):

<x-app-layout>
    <x-スロット名="ヘッダー">{{ __('管理') }}</x-スロット>
    <div>




<hr>

<p><strong>出力</strong></p>

<p>ここで得られる最終出力は次のとおりです:</p>

<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173418649412401.jpg" class="lazy" alt="Building Dynamic and Maintainable Menus in Laravel"></p>
<blockquote>
<p>私の仕事を後援することで、開発者コミュニティに力を與えるという私の使命をサポートしてください。あなたの貢獻(xiàn)は、貴重なツール、洞察、リソースを構(gòu)築して共有するのに役立ちます。詳細(xì)については、こちらをご覧ください。</p>
</blockquote>


<hr>

<h3>
  
  
  <strong>結(jié)論</strong>
</h3>

<p>この<strong>メニュービルダーシステム</strong>は、次の方法でLaravelのナビゲーション管理を簡素化します。</p>

<ol>
<li>メニュー定義を一元化して保守性を向上させます。</li>
<li>役割または権限を使用してメニューの表示を動(dòng)的に制御します。</li>
<li>ビューとレイアウト間でメニュー ロジックを再利用します。</li>
</ol>

<p>このアプローチを採用すると、複雑なアプリケーションであってもナビゲーション システムをシームレスに拡張できます。 </p>

<p>データベースからメニューの詳細(xì)をロードし、必要なメニューを構(gòu)築することもできます。しかし、私にとってはこれで十分です。データベース主導(dǎo)のメニュー構(gòu)成を使用する必要があるプロジェクトはありません。</p>

<p>コードはここにあります。 </p>

<p>試して感想をシェアしてください! ?</p>


<hr>

<p>Unsplash の LinedPhoto による寫真</p>


          </div>

            
  

            
        </x-app-layout>

以上がLaravel で動(dòng)的で保守可能なメニューを構(gòu)築するの詳細(xì)內(nèi)容です。詳細(xì)については、PHP 中國語 Web サイトの他の関連記事を參照してください。

このウェブサイトの聲明
この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當(dāng)する法的責(zé)任を負(fù)いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脫衣畫像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード寫真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

寫真から衣服を削除するオンライン AI ツール。

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中國語版

SublimeText3 中國語版

中國語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強(qiáng)力な PHP 統(tǒng)合開発環(huán)境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

PHPに認(rèn)証と承認(rèn)を?qū)g裝するにはどうすればよいですか? PHPに認(rèn)証と承認(rèn)を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM

tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole

PHPでファイルアップロードを安全に処理するにはどうすればよいですか? PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM

PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認(rèn)し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認(rèn)し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強(qiáng)化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認(rèn)します。

PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM

PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。

PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM

はい、PHPは、特定の拡張機(jī)能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機(jī)能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。

PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM

PHPで基本的な數(shù)學(xué)操作を使用する方法は次のとおりです。1。追加標(biāo)識(shí)は、整數(shù)と浮動(dòng)小數(shù)點(diǎn)數(shù)をサポートし、変數(shù)にも使用できます。文字列番號(hào)は自動(dòng)的に変換されますが、依存関係には推奨されません。 2。減算標(biāo)識(shí)の使用 - 標(biāo)識(shí)、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標(biāo)識(shí)を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標(biāo)識(shí)を使用し、結(jié)果は浮動(dòng)小數(shù)點(diǎn)數(shù)である可能性があることに注意してください。 5.モジュラス標(biāo)識(shí)を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負(fù)の數(shù)を処理する場合、殘りの兆候は配當(dāng)と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。

最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM

postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests.

PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM

PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions

PHPタイムゾーンを設(shè)定する方法は? PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM

tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset.

See all articles