Laravel框架illuminate\support\collection排序问题技术
maybe yes 发表于2015-04-03 00:59
Laravel 的 Collection 的排序有个问题,前几天折腾了好久,一直怀疑是自己代码有问题。Collection 对象执行 sort 后需要执行 values 方法,否则 Collection 对象的 items 排序结果没有生效。当然手动的 toArray() 是生效的。查看 Collection sort 方法内部实现是调用了 PHP 的 uasort 函数,该函数排序后会维持原来的 key => value 关系。
官方文档截取如下:
Collection values()Reset the keys on the underlying array.Return ValueCollection
一直弄不明白,为什么这个方法叫 values,这个取名真让人费解,values 方法内部使用 array_values 方法对 items 进行了重新赋值。有时候,开发特别折腾,一直在更改... 代码片段如下,需要调用 values 方法使得排序生效。
$left = $right = null;switch($sortby){ case "rating": case "month_sales": $left = -1; $right = 1; break; case "order_lead_time": case "minimum_order_amount": $left = 1; $right = -1; break;}if($ascending === "1"){ $left = 1; $right = -1;}elseif($ascending === "0"){ $left = -1; $right = 1;}$restaurants->sort(function($a, $b) use ($sortby, $left, $right){ return ($a->{$sortby} >= $b->{$sortby}) ? $left : $right;});$restaurants->values();
开发过程中特别的挑刺,过分的在乎变量命名和参数方式,过早的优化代码,都是不好的。这个世界上应该没有哪两家的公司的业务是完全一样的,用了太多的开源软件也不一定是好事。顺便评价下 Laravel,传说中的 Artisan,我感觉用起来很不舒畅,错误日志不打印日期,不打印哪里出错,叫人怎么调试。
sort 方法 和 values 方法内部实现代码:
public function sort(Closure $callback){ uasort($this->items, $callback); return $this;}public function values(){ $this->items = array_values($this->items); return $this;}
阅(498)评(0)查看评论

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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