首页 > 后端开发 > php教程 > 用可弦的属性简化您的Laravel模型

用可弦的属性简化您的Laravel模型

Robert Michael Kim
发布: 2025-03-05 15:43:23
原创
376 人浏览过

Streamline Your Laravel Models with Stringable Attributes

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中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板