Uncover Laravel's Hidden Treasures
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
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' ]);
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);
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; });
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); });
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);
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();
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; }
We can even convert articles to regular arrays or their JSON representation.
$array = $articles->toArray(); $json = $articles->toJson();
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');
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; }
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');
在此示例中,我们创建一个 restricted
过滤器,它需要一个参数 $group
。 $route
和 $request
参数始终提供给 before 过滤器。
但是如果我们想要更大的灵活性怎么办?假设我们想要将过滤器应用于所有 admin
路由除了 admin/login
。我们可以使用路线组并将相关路线移至组外。或者我们可以使用 Route::whenRegex
并编写我们自己的正则表达式。
Route::whenRegex('/^admin(\/(?!login)\S+)?$/', 'restricted:admin');
此正则表达式只是确保它仅适用于以 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
您实际上可以完全删除 if
语句,并使用 first
方法的第二个参数将消息包装在 div
中。
{{ Form::text('username', null) }} {{ $errors->first('username', '<div class="error">:message</div>') }}
好多了,好多了!
流利
可用时间: v3.0.0
记录:部分
Fluent
类已经存在很长时间了,当使用模式生成器创建迁移时,它实际上在框架本身内使用。 Laravel 3 和 Laravel 4 之间,类本身几乎没有变化,唯一大的区别是多了一些接口。
要使用 Fluent
类,您所需要做的就是获取一个实例,然后就可以了。
$user = new Illuminate\Support\Fluent; $user->name('Jason')->country('Australia')->subscriber();
该实例现在定义了 3 个属性:name
,值为 Jason
、country
,值为 Australia
和 subscriber
,值为布尔值 true
。
在 Laravel 4.1 之前,您只能从实例中真正设置和获取属性。从 Laravel 4.1 开始,您可以使用 toArray
和 toJson
方法分别获取属性数组及其 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

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,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

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.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

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�...
