Table of Contents
Preview
Code Example
不同的视角
Home Backend Development PHP Tutorial How to write code using Laravel Collections class

How to write code using Laravel Collections class

Jul 10, 2018 pm 02:02 PM
collection laravel php tutorial Tutorial

This article mainly introduces how to write code using the Laravel Collections class. It has certain reference value. Now I share it with you. Friends in need can refer to it

Laravel provides some awesome components , in my opinion, it is the one that provides the best component support among all current web frameworks. It not only provides out-of-the-box views, authentication, sessions, caching, Eloquent, queues, data validation and other components. There are even development tools provided (Valet and Homestead).

However, the most powerful feature of this framework is often ignored by newcomers - the Collection (collection) class. In this article, we'll explore how to use collections to improve coding efficiency, readable lines of code, and write leaner code.

Preview

The initial exposure to using collections came from developers using Eloquent to execute database queries and using the foreach statement to traverse the model collection from the returned data.

However, beginners may not notice that collections provide more than 90 methods to operate on the underlying data. What's even better is that almost all methods support chaining operations, making your code read like prose. This makes your code easier to read, both for you and other users.

Haven’t gotten to the point yet? Okay, let’s review a simple code snippet and see how we can use collections to write thick, fast, and powerful code.

Code Example

Let's build a real world. Suppose we query some API interfaces and obtain the following result set saved in an array:

<?php
// API 请求返回的结果
$data = [
    [&#39;first_name&#39; => 'John', 'last_name' => 'Doe', 'age' => 'twenties'],
    ['first_name' => 'Fred', 'last_name' => 'Ali', 'age' => 'thirties'],
    ['first_name' => 'Alex', 'last_name' => 'Cho', 'age' => 'thirties'],
];
Copy after login

We see that the array contains first name, last name and age range. Now, we assume that we get a age(age) user with 30 years old(thirties) from the record, and then proceed# based on the last name(last name) ##Sort(sort). Finally, we also hope that the returned result is a single string, so that each user has an exclusive new line. Finally, we also hope that the returned result is

This requirement seems not difficult to achieve, now let us see how to implement this function using PHP:

// 依据姓氏排序
usort($data, function ($item1, $item2) {
    return $item1['last_name'] <=> $item2['last_name'];
});

// 依据年龄范围分组
$new_data = [];

foreach ($data as $key => $item) {
    $new_data[$item['age']][$key] = $item;
}

ksort($new_data, SORT_NUMERIC);

// 从年龄为 30 岁组里获取用户全名
$result = array_map(function($item) {
    return $item['first_name'].' '.$item['last_name'];
}, $new_data['thirties']);

// 将数组转换为字符串并以行分隔符分隔
$final = implode("\n", $result);

// 译注:原文是 $final = implode($results, "\n"); implode函数接收两种顺序的参数,为了保持与文档一致所以我这边做了调整。
Copy after login
Our implementation code exceeds 20 lines , and very inelegant. Remove comments and newline-related code, and this code will become difficult to read. Furthermore, we also need to use temporary variables and the unfriendly sort method built into PHP.

Now, let’s see how simple it is with the Collection class:

collection($data)->where('age', 'thirties')
                 ->sortBy('last_name')
                 ->map(function($item){
                    return $item['first_name'].' '.$item['last_name'];
                 })
                 ->implode("\n");
Copy after login
Wow! Our code went from 20 lines to 6 lines. Not only does the code now run much smoother, but methods are implemented without the need for comments to tell us what problem they are dealing with.

However, there is still one problem that prevents our code from being as good as the perfect stage... It is the

map method used to compare first name and last name. Frankly, this isn't really a big deal, but it provides motivation for exploring macro concepts.

Extending Collections

The Collection class, like other Laravel components, supports macros, which means you can add methods to it and use them later.

Tip: If you want new methods to be available everywhere, you should add them to the service provider. I like to create a MacroServiceProvider to implement this function, whichever you like.
Let's add a method that will concatenate any number of fields provided by the array and return a string result:

Collection::macro('toConcatenatedString', function ($fields = [], $separator = ' ') {
    return $this->map(function($item) use ($fields, $separator) {
        return implode($separator, array_map(function ($el) use ($item) {
                return $item[$el];
            }, $fields)
        );
    })->implode("\n");
});
Copy after login
After adding this method, our code is basically perfect:

collect($data)->where('age', 'thirties')
              ->sortBy('last_name')
              ->toConcatenatedString(['first_name', 'last_name']);
Copy after login
Our code has been streamlined from more than 20 chaotic lines to 3 lines. The code is clean and tidy and has clear functions that anyone can understand immediately.

Another example

Now let’s look at the second example, assuming we have a list of users, we need to filter them out based on role, and then further if their registration time is 5 Years or older and

last name starts with the letters A-M only gets the first user.

The data is similar to the following:

<?php
// API 请求返回的结果
$users = [
    [&#39;name&#39; => 'John Doe', 'role' => 'vip', 'years' => 7],
    ['name' => 'Fred Ali', 'role' => 'vip', 'years' => 3],
    ['name' => 'Alex Cho', 'role' => 'user', 'years' => 9],
];
Copy after login
If we are using PHP implementation, our code looks as follows:

$subset = [];
foreach ($users as $user) {
    if ($user['role'] === 'vip' && $user['years'] >= 5) {
        if (preg_match('/\s[A-Z]/', $user['name'])) {
            $subset[] = $user;
        }
    }
}
return reset($subset)
Copy after login
Note: You can The second if statement is moved inside the first one, but I personally like to use no more than two conditionals in a single if statement because I think more than 2 conditionals make the code difficult to read.
This code is not too bad, but we still need to use temporary variables, and we also need to use the

reset function to reset the pointer to the first user. Our code also has four levels of indentation, which makes parsing the code more challenging.

Instead, let’s see how collections handle this problem:

collect($users)->where('role', 'vip')
              ->map(function($user) {
                  return preg_match('/\s[A-Z]/', $user['name']);
              })
              ->firstWhere('years', '>=', '5');
Copy after login

我们将代码简化到了之前的一般左右,每一步过滤处理清晰明了,并且我们不需要引入临时变量。

遗憾的是目前集合还不支持正则匹配,所以我们使用 map 方法,不过我们可以为这个功能创建一个宏:

Collection::macro('whereRegex', function($expression, $field) {
    return $this->map(function ($item) use ($expression, $field) {
        return preg_match($expression, $item[$field]);
    })
});
Copy after login

得益于宏方法,我们的代码现在看起来如下:

collect($users) -> where('role', 'vip')
                -> whereRegex('/\s[A-Z]/', 'name')
                -> firstWhere('years', '>=', 5);
Copy after login
注意:  为了简单起见,我们的红仅仅适用于数组集合。如果你计划让它们可以在 Eloquent 集合上使用,你需要在此场景下做相应的代码处理才行。

不同的视角

我们可以继续列出无数的示例,但仍然无法涵盖所有可用的集合方法,并且这从来都不是本文的真正目的。

需要注意的是,通过使用 Collection 类,您不仅可以获得一个方法库来简化编程工作,还可以选择一种从根本上改善代码的方法。

你会情不自禁的将你的代码结构从代码块重构简化成一行,同时减少代码的缩进,临时变量的使用和技巧性方法,另外你还可以使用链式编程方法,这让你的代码更加便于阅读和解析,此外最重要的是减少了编码工作!

查看官方文档获取更多这个迷人的类库的使用细节:https://laravel.com/docs/coll...

提示: 你还可以获取这个 Collection 类独立安装包,在使用非 laravel 项目是会非常有帮助。感谢 Tighten Co 团队做出的努力 https://github.com/tightenco/...。

感谢阅读,快乐编码!

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于Laravel的Eloquent ORM的解析

The above is the detailed content of How to write code using Laravel Collections class. 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)

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.

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

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: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles