Laravel 的 AsStringable
类型转换器是一个强大的工具,可以显着增强您在 Eloquent 模型中处理字符串属性的方式。通过将字符串属性转换为 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中文网其他相关文章!