ホームページ >バックエンド開発 >PHPチュートリアル >Laravelモデルをストリング可能な属性で合理化します
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 サイトの他の関連記事を参照してください。