ホームページ >バックエンド開発 >PHPチュートリアル >Laravelモデルをストリング可能な属性で合理化します

Laravelモデルをストリング可能な属性で合理化します

Robert Michael Kim
Robert Michael Kimオリジナル
2025-03-05 15:43:23376ブラウズ

Streamline Your Laravel Models with Stringable Attributes

laravelのAsStringableタイプコンバーターは、雄弁モデルの文字列プロパティを処理する方法を大幅に強化する強力なツールです。文字列プロパティをStringableオブジェクトに変換することにより、多数の文字列操作方法にアクセスして、よりクリーナーとより表現力のあるコードを書き込むことができます。

この方法は、文字列操作が頻繁に存在するコンテンツ集約型アプリケーションに特に役立ち、コントローラーを維持し、整頓されたものを把握するのに役立ちます。

use Illuminate\Database\Eloquent\Casts\AsStringable;

class Post extends Model
{
    protected function casts(): array
    {
        return [
            'title' => AsStringable::class,
            'content' => AsStringable::class
        ];
    }
}

コンテンツ管理システムの実用的な例は次のとおりです。

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\AsStringable;

class Article extends Model
{
    protected function casts(): array
    {
        return [
            'title' => AsStringable::class,
            'content' => AsStringable::class,
            'meta_description' => AsStringable::class
        ];
    }

    public function getSnippetAttribute()
    {
        return $this->content
            ->stripTags()
            ->words(30, '...');
    }

    public function getUrlPathAttribute()
    {
        return $this->title
            ->slug()
            ->prepend('/articles/');
    }

    public function getFormattedContentAttribute()
    {
        return $this->content
            ->markdown()
            ->replaceMatches('/\@mention\((.*?)\)/', '<a href="https://www.php.cn/link/2fc02e925955d516a04e54a633f05608">@</a>')
            ->replace('[[', '<mark>')
            ->replace(']]', '</mark>');
    }

    public function getSeoTitleAttribute()
    {
        return $this->title
            ->title()
            ->limit(60);
    }
}
$article = Article::find(1);
// 直接访问 Stringable 方法
dd($article->title->title());
dd($article->content->words(20));

// 使用计算属性
dd($article->snippet);
dd($article->url_path);
dd($article->formatted_content);

AsStringable

>タイプコンバーターは、コードのシンプルさと保守性を維持しながら、文字列処理をエレガントなメソッドコールエクスペリエンスに変換します。

以上がLaravelモデルをストリング可能な属性で合理化しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。