Table of Contents
Cascading View
gather
Sort
filter
Paging
there are more!
Regular Expression Filter
消息包
流利
还有更多!
Home Backend Development PHP Tutorial Uncover Laravel's Hidden Treasures

Uncover Laravel's Hidden Treasures

Aug 28, 2023 pm 04:45 PM

揭开 Laravel 隐藏的宝藏

Many developers using Laravel may have only scratched the surface of what the framework has to offer. While the documentation does cover the most common use cases and obvious features, it doesn't cover everything.

Don't get me wrong, the documentation is great, it's just that there are so many things you can do that it's hard to document everything. So, we’re going to take a look at some of the hidden gems lurking in Laravel.

Cascading View

Available time: v4.0.0

Record:No

Views can be cascaded like configuration files. Cascading views are very useful when developing scalable theming systems. Consider the following directory structure.

/app
    /views
        /blog
            /index.blade.php
/themes
    /default
        /views
            /blog
                /index.blade.php
            /theme.blade.php
Copy after login

The idea is that when we return View::make('theme::blog.index'); it will first be in the themes/default/views directory Search, find the view if not found, fall back to app/views.

To do this, we use View::addNamespace to register our own namespace in both locations.

View::addNamespace('theme', [
    base_path().'/themes/default/views',
    app_path().'/views'
]);
Copy after login

gather

Available time: v4.0.0

Record:Part

Collections are a great way to interact with and manage arrays. Collections have a variety of convenience methods and implement many useful interfaces, such as ArrayableInterface, IteratorAggregate, and JsonableInterface.

Suppose we are building a small blog engine that uses flat files for storage. We want to be able to perform operations such as sorting, filtering, and paging.

Implementing a blog engine is beyond the scope of this article, but assume we have an array $articles, and each member of the array is an instance of the Article class. Then all we need to do is get a new instance of Collection and give it our array of articles.

$articles = new Illuminate\Support\Collection($arrayOfArticles);
Copy after login

Sort

Using collections we can sort articles. Let’s sort the articles and display the most recently updated ones first. For the purposes of this article, we assume that when loading an article from the file system, we set the updatedAt attribute to the last modification time of the file.

$articles->sortByDesc(function ($article) { 
    return $article->updatedAt; 
});
Copy after login
The

sortBy and sortByDesc methods accept a callback that should return a value that can be used to sort the collection. In our case, we can simply return the last modification time of the article, and the collection can be sorted based on that time.

filter

Similar to sorting, we can also use collections to filter our articles, just like the WHERE clause in MySQL. Let's filter our articles based on searches that may have been run.

<?php

$searchQuery = 'Laravel rocks!';

$results = $articles->filter(function ($article) use ($searchQuery) {
    return preg_match(sprintf('/%s/m', $searchQuery), $article->body);
});
Copy after login
The

filter method actually returns a new instance of Illuminate\Support\Collection, so we need to assign it to the $results variable. This new collection will only contain articles that mention "Laravel rock!"

Paging

Using this collection, we can paginate articles so that there are not too many articles on a single page.

$perPage = 1;

$page = Input::get('page', 1);

if ($page > ($articles->count() / $perPage)) {
    $page = 1;
}

$pageOffset = ($page * $perPage) - $perPage;

$results = $articles->slice($pageOffset, $perPage);
Copy after login

Using the slice method, we extract a portion of the articles in the collection and assign it to the $results variable.

This example can be further implemented by creating a new instance of Laravel's Paginator class. This way it can generate all the page numbers and links for you.

there are more!

We can get a random article:

$article = $articles->random();
Copy after login

We can also iterate over our collection of articles as if it were a regular array. This is all thanks to the IteratorAggregate and ArrayIterator interfaces.

foreach ($articles as $article) {
    echo $article->body;
}
Copy after login

We can even convert articles to regular arrays or their JSON representation.

$array = $articles->toArray();
$json = $articles->toJson();
Copy after login

One of the coolest methods is probably groupBy, which allows us to group articles by a specific key. Imagine that each article has some metadata at the top that is parsed and removed from the article body.

Although parsing this metadata is beyond the scope of this article, we assume it is parsed and is a property on the Article instance. You can then use groupBy to group the articles by the category they were published in.

$results = $articles->groupBy('category');
Copy after login

All articles sharing the same category will be grouped. Then you can get articles in a specific category.

foreach ($results->get('tutorial') as $article) { 
    echo $article->body; 
}
Copy after login

Collections are one of the best hidden gems Laravel has to offer.

Regular Expression Filter

Available time: v4.1.19

Record:No

Filtering routes in Laravel is a common task that many of us perform in all our projects. Filters allow you to perform tasks such as user authentication or rate limiting before or after a route is triggered. We create filters using Route::filter and can apply them to individual routes, route groups, or use Route::when and apply to matching patterns.

Route::filter('restricted', function($route, $request, $group)
{
    // Restrict user access based on the value of $group
});

Route::when('admin/*', 'restricted:admin');
Copy after login

在此示例中,我们创建一个 restricted 过滤器,它需要一个参数 $group$route$request 参数始终提供给 before 过滤器。

但是如果我们想要更大的灵活性怎么办?假设我们想要将过滤器应用于所有 admin 路由除了 admin/login。我们可以使用路线组并将相关路线移至组外。或者我们可以使用 Route::whenRegex 并编写我们自己的正则表达式。

Route::whenRegex('/^admin(\/(?!login)\S+)?$/', 'restricted:admin');
Copy after login

此正则表达式只是确保它仅适用于以 admin 开头且后面不跟 /login 的路由,但后面可以跟任何其他内容。出色的。现在,我们将 restricted:admin 过滤器应用于除 admin/login 路由之外的所有路由。

消息包

可用时间: v4.0.0

记录:部分

毫无疑问,您已经使用 Illuminate\Support\MessageBag 一段时间了,甚至没有意识到。 MessageBag 扮演的最大角色是在使用 Laravel 内置验证器时包含所有验证错误。

每个视图中都有一个 $errors 变量,该变量包含空的 MessageBag 实例或使用 Redirect::to('/')->withErrors($validator); 刷新到会话的实例

当在特定输入下方显示错误消息时,很多人可能会在表单中执行类似的操作。

{{ Form::text('username', null) }}
@if($errors->has('username'))
    <div class="error">{{ $errors->first('username') }}></div>;
@endif
Copy after login

您实际上可以完全删除 if 语句,并使用 first 方法的第二个参数将消息包装在 div 中。

    {{ Form::text('username', null) }}
    {{ $errors->first('username', '<div class="error">:message</div>') }}
Copy after login

好多了,好多了!

流利

可用时间: v3.0.0

记录:部分

Fluent 类已经存在很长时间了,当使用模式生成器创建迁移时,它实际上在框架本身内使用。 Laravel 3 和 Laravel 4 之间,类本身几乎没有变化,唯一大的区别是多了一些接口。

要使用 Fluent 类,您所需要做的就是获取一个实例,然后就可以了。

$user = new Illuminate\Support\Fluent;
$user->name('Jason')->country('Australia')->subscriber();
Copy after login

该实例现在定义了 3 个属性:name,值为 Jasoncountry,值为 Australiasubscriber,值为布尔值 true

在 Laravel 4.1 之前,您只能从实例中真正设置和获取属性。从 Laravel 4.1 开始,您可以使用 toArraytoJson 方法分别获取属性数组及其 JSON 表示形式。

从 Laravel 4.2 开始,该类还实现了 JsonSerialized 接口,这意味着您可以将实例直接传递到 json_encode 中。

还有更多!

我们已经研究了 Laravel 框架的几个有用的精华。但是,正如您所猜测的,框架内还有更多内容。

了解 Laravel 可能提供的其他功能的最佳方法是深入研究源代码。它并不像您想象的那么可怕,您将学到很多关于您正在构建的框架的知识。

如果您发现了其他宝石,请随时在评论中分享!

The above is the detailed content of Uncover Laravel's Hidden Treasures. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? Apr 01, 2025 pm 03:09 PM

An official introduction to the non-blocking feature of ReactPHP in-depth interpretation of ReactPHP's non-blocking feature has aroused many developers' questions: "ReactPHPisnon-blockingbydefault...

See all articles