Table of Contents
自定义方法" >自定义方法
Home PHP Framework Laravel Share 2 tips for using Laravel models

Share 2 tips for using Laravel models

Oct 09, 2020 pm 02:38 PM
laravel php

下面由Laravel教程栏目给大家分享Laravel模型使用的2个小技巧 ,希望对需要的朋友有所帮助!

Share 2 tips for using Laravel models

引言

本文说说模型的修改器,以及模型的职责。

修改器

有没有这样一种用法:使用表单获取一个字段的输入,使用加密算法,或者摘要方式对字段处理后存入数据库,

这在数据库密码字段是常用的处理手段。

如果写操作在程序内到处都是,零散地分布在业务代码的各个地方,我们总不至于每次都要写一次相同的代码吧?

相同的业务逻辑,提取出来,抽象出来,只写一次,这才是高效代码的王道。

laravel这个注重设计模式的现代化框架,自然是不会做无用功。于是对应读取器,就有了修改器,专门用于写入数据库时起作用。

比如对于写操作,某个字段的值写入,默认使用 bcrypt 方法加密之后存入数据库。

class User extends Model {
    public function setPasswordAttribute($password)
    {
        $this->attributes['password'] = bcrypt($password);
    }}
Copy after login

上述方法调用模型的 $attributes 属性,并使用自定义方法改写,在使用 ->password 属性进行赋值后,就会调用该方法的代码并执行。

我们仍然在 tinker 内进行演示:

$user = new User;$user->password = 'blah';echo $user->password;// 输出 $2y$10$e3ufaNvBFWM/SeFc4ZyAhe8u5UR/K0ZUc5IjCPUvOYv6IVuk7Be7q
Copy after login

框架独立出来模型这个数据库操作层的目的,就是为了把数据操作全部集中到模型内完成,以便可以全局统一,规范地编写代码。

下面举个例子,说明一下哪些逻辑应该放在模型层操作。比如有一个视图文件内的一个展示片段:

@if ($event->started_at->isToday())
    This event is occurring today!@endif
Copy after login

其中 $event 是模型 Event 对象的一个实例,start_at 方法是模型的一个属性,也是数据库表的一个字段。按照之前章节的介绍,我们对其使用了访问器的方法,自动在读取的时候使用 Carbon 类返回一个实例化对象。所以上面的代码片段可以使用 isToday() 这个 Carbon 类的方法。

但是在模型层面进行类库方法的调用,有些单独,且零散。假如有些API接口要使用此方法格式化,或者别的页面也要重用这个方法,显然放在模型内更为合适。

考虑在模型内添加以下代码:

class Event extends Model {
    public function occurringToday()
    {
        return $this->started_at->isToday();
    }}
Copy after login

声明一个public的公开访问的私有化方法,并操作对象的实例 $this的属性和方法。

那么上述的blade模板内的代码就可以更换如下:

@if ($event->occurringToday())
    This event is occurring today!@endif
Copy after login

这样逻辑摘出来就清楚的多了。而且可维护性更强。为什么?因为假如后期我们业务出现变动,不再使用 start_at 字段进行判断,可以很容易地通过修改 occurringToday 方法而达成全局生效的目的。

这样的程序就很灵活了。

写在最后

本文描述了laravel模型内很常用的两个小技巧。

  • 一个是修改器,让你不必每次在写入数据的时候,考虑如何转换,如何判断,不再写重复的啰嗦的代码;

  • 一个是如何优化视图文件,以及如何权衡设计技巧,让模型做模型应该做的事情,尽量在代码内把职责划分清楚。

规范的设计,能让一个项目的代码更为健壮。

The above is the detailed content of Share 2 tips for using Laravel models. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

Laravel's geospatial: Optimization of interactive maps and large amounts of data Laravel's geospatial: Optimization of interactive maps and large amounts of data Apr 08, 2025 pm 12:24 PM

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

Laravel and the Backend: Powering Web Application Logic Laravel and the Backend: Powering Web Application Logic Apr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles