>백엔드 개발 >PHP 튜토리얼 >스트링 가능한 속성으로 라벨 모델을 간소화하십시오

스트링 가능한 속성으로 라벨 모델을 간소화하십시오

Robert Michael Kim
Robert Michael Kim원래의
2025-03-05 15:43:23372검색

Laravel 's

유형 변환기는 웅변 모델에서 문자열 속성을 처리하는 방식을 크게 향상시키는 강력한 도구입니다. 문자열 속성을 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);
    }
}

위 내용은 스트링 가능한 속성으로 라벨 모델을 간소화하십시오의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.