Posts tagged with best practices

Partial model updates in Laravel

Michael Dyrynda, one of the co-hosts of the Laravel News and the North Meets South podcasts, explains how to easily uptime your models with data coming from requests.

Instead of littering your controller method with multiple request()->has('field') checks, you can employ the request object's intersect method. The intersect method will return a new array containing only the keys that are present in both the specified list and the request itself.

Using intersect allows you to easily handle a PATCH request - one where you partially update a resource's data, rather than all of it as with a PUT - in a much more concise manner.

https://dyrynda.com.au/blog/partial-model-updates-in-laravel

Read more

How we improved our PWA score by 53 points in 4 hours

On the madewithlove blog Frederick Vanbrabant wrote a post on how he and colleague improved the PWA score of their company site.

So the first thing you should know about PWA (or progressive web apps) is that it’s an adaptation of your current site or web app. This means that if you want to have all the features of a progressive web app, you are going to need to change your current site/application. The good news here is that they are all changes you would want to have anyway.

https://blog.madewithlove.be/post/improved_pwa_score

Read more

Join 9,000+ developers

Every month, I share practical tips, tutorials, and behind-the-scenes insights from maintaining 300+ open source packages.

No spam. Unsubscribe anytime. You can also follow me on X.

Closure Binding as an alternative to “use” variables

On his blog Mark Baker shares some thoughts on how to use closure binding to avoid having import variables with the use keyword.

You'll learn how to rewrite

$filteredArrayData = array_filter(
    $arrayData,
    function($value) use ($minimumPrice, $maximumPrice) {
        return $value->price >= $minimumPrice &amp;&amp; $value->price < $maximumPrice;
    }
);

to

$filteredArrayData = array_filter(
    $bookData,
    $priceFilter->inRange(5.00, 15.00)
);

https://markbakeruk.net/2017/03/12/closure-binding-as-an-alternative-to-use-variables/

Read more

Non-breaking, SEO Friendly Url's in Laravel

Sebastian De Deyne, author of many Spatie packages, posted a new blog article on how to generate SEO Friendly Urls in Laravel.

When admins create or update an news item—or any other entity—in our homegrown CMS, a url slug is generated based on it's title. The downside here is that when the title changes, the old url would break. On the other hand, if we wouldn't regenerate the url on updates, titles that were edited later on would still have an old slug in the url, which isn't an ideal situation either.

https://sebastiandedeyne.com/posts/2017/non-breaking-seo-friendly-urls-in-laravel

Read more

Polyfills: everything you ever wanted to know, or maybe a bit less

David Gilbertson tells you all about polyfills.

Faced with the reality that you can’t write modern code and expect it to work for all users, you have exactly two choices:
  1. Only use language features available in all the browsers you support
  2. Write modern code, then do something to make it work in older browsers

If you have decided on option one then I respectfully suggest that you are bonkers, and insist that you state your case in the comments. I believe that developers who are able to explore all the new stuff and use it in their day-to-day jobs stay happy, and being happy is important.

https://hackernoon.com/polyfills-everything-you-ever-wanted-to-know-or-maybe-a-bit-less-7c8de164e423

Read more

Configuration-driven PHP security advice considered harmful

Scott Arciszewski debunks the commonly given advice on securing your PHP installation by setting some php.ini values.

There have been countless examples posted in various places (Reddit, Hacker News, Twitter, Facebook, Slashdot, and even LinkedIn group discussions), and while a handful occasionally contain one or two tips that might be beneficial towards securing your PHP applications, almost all of the advice they contain is either wrong, a huge waste of time, downright silly, or all of above.

As part of a team that specializes in application security (in particular: securing PHP applications), I feel it's high time someone cleared the air about this advice.

https://paragonie.com/blog/2017/01/configuration-driven-php-security-advice-considered-harmful

Read more

A checklist for all projects that are going live original

by Freek Van der Herten – 2 minute read

Apart from our open source work, we do client work at Spatie as well. Over the years we've learned that one of the most critical moments of a project is when it is going live. No matter how you confident you are about the correctness of the code base there are so many big and little things that…

Read more

The Magic Tricks of Testing

In a mail sent to all subscribers on the testdrivenlaravel.com-mailinglist Adam Wathan mentioned a talk Sandi Metz gave a couple of years ago at Rails Conf. It's a really good talk that explains in a clear way when and what you should test.

Tests are supposed to save us money. How is it, then, that many times they become millstones around our necks, gradually morphing into fragile, breakable things that raise the cost of change? We write too many tests and we test the wrong kinds of things. This talk strips away the veil and offers simple, practical guidelines for choosing what to test and how to test it. Finding the right testing balance isn't magic, it's a magic trick; come and learn the secret of writing stable tests that protect your application at the lowest possible cost.

Read more

Use sane defaults over exceptions

Freek Lijten, a developer at Schiphol, makes the case for just setting a sane default value instead of throwing an exception when invalid input entered the application.

I didn't think much of this, but I've seen a major drawback lately while working on a site that is a bit bigger than I was used to. With over half a million visitors a week and lots of scrapers, bots and other stuff visiting, these exceptions and fatal errors clog up logging quite a bit. Not to the point that we can't handle the volume, but it generates false positives in monitoring channels and it is something we do not want to act upon anyway.

http://www.freeklijten.nl/2017/01/04/Sane-defaults-over-Exceptions

Read more

Conditionally adding rules to a validator in Laravel

Mohamed Said explains the not so well known sometimes validation rule in Laravel.

Laravel's validation library is very powerful and easy to use, using a few keystrokes you can build a strong defence around your application, preventing invalid user input from corrupting the application flow and potentially introducing bugs.

...

In this post I'd like to highlight a trick related to conditionally adding validation rules.

http://themsaid.com/laravel-advanced-validation-conditionally-adding-rules-20170110/

To learn more read the relevant section in the Laravel docs.

Read more

Why I close PRs

Jeff Geerling, currently working as a technical architect at Aquina, wrote a good post on when and why he closes PRs to the packages he's maintaining. This paragraph resonated with me.

I don't cater to everyone. I usually cater to myself. And for 98% of my OSS projects, I'm actually using them, live, in production (often for dozens or hundreds of projects). So I'm generally happy with them as they are. I will not add something that increases my maintenance burden unless it's very compelling functionality or an obvious bugfix. I can't maintain a system I don't fully understand, so I like keeping things lighter and cutting off edge cases rather than adding technical debt I don't have time to pay off.

http://www.jeffgeerling.com/blog/2016/why-i-close-prs-oss-project-maintainer-notes

Read more

10 things I learned making the fastest site in the world

David Gilbertson made a lighting fast site and wrote a fantastic article about it.

Writing a fast website is like raising a puppy, it requires constancy and consistency (both over time and from everyone involved). You can do a great job keeping everything lean and mean, but if you get sloppy and use an 11 KB library to format a date and let the puppy shit in the bed just one time, you’ve undone a lot of hard work and have some cleaning up to do.

https://hackernoon.com/10-things-i-learned-making-the-fastest-site-in-the-world-18a0e1cdf4a7

Read more

PHP 5: Active Support Ends. Now what?

Starting from tomorrow PHP 5.6. will not be actively supported anymore. Sebastian Bergmann, author of PHPUnit explains how PHP's release process works, and what the ending of active support means for you. Spoiler: you should upgrade asap.

It is high time to think about upgrading your PHP stack to PHP 7, ideally to PHP 7.1. This should be a short-term goal for you.

Upgrading the version of PHP you use must not be a rare event you are afraid of. You must not think of upgrading your PHP stack as a "special project". You need to make upgrading the PHP version you use part of your normal operational procedure and align the upgrade cycle of your PHP stack with the release cycle of the PHP project. This should be a long-term goal for you.

https://thephp.cc/news/2016/12/php-5-active-support-ends-now-what

Read more

Optimizing PHP performance by using fully-qualified function calls

A fully qualified function name is a little bit faster than a non-qualified one. Toon Verwerft explains it all in his lastest blogpost.

Today, a little conversation on Twitter escalated rather quickly. Apparently PHP runs function calls differently depending on namespaced or non namespaced context. When calling functions in a namespaced context, additional actions are triggered in PHP which result in slower execution. In this article, I'll explain what happens and how you can speed up your application.

http://veewee.github.io/blog/optimizing-php-performance-by-fq-function-calls/

Read more

The delicious evils of PHP

In a post on Sitepoint Christopher Pitt demonstrates some cool usages of eval and exec.

I want to look at two PHP functions: eval and exec. They’re so often thrown under the sensible-developers-never-use-these bus that I sometimes wonder how many awesome applications we miss out on.

Like every other function in the standard library, these have their uses. They can be abused. Their danger lies in the amount of flexibility and power they offer even the most novice of developers.

Let me show you some of the ways I’ve seen these used, and then we can talk about safety precautions and moderation.

https://www.sitepoint.com/the-delicious-evils-of-php/

Read more

How I refactor to collections

Christopher Rumpel posted some good practical examples on how to refactor common loops to collections.

Refactoring to Collections is a great book by Adam Wathan where he demonstrates, how you can avoid loops by using collections. It sounds great from the beginning, but you need to practice it, in order to be able to use it in your own projects. This is why I refactored some of my older projects. I want to share these examples today with you.

http://christoph-rumpel.com/2016/11/How-I-refactor-to-collections/

Read more

Does code need to be perfect?

Andreas Creten explains his view on wether you should always try to write perfect code. Spoiler: no.

The engineers want to write perfect code using the latest techniques, make sure that the code is well documented so they can fully understand how everything works and that it has tests so they can easily update things later. Product owners on the other hand just want things to be done, fast and cheap, so they can ship new features or convince new clients. How can you make these conflicting views work together?

https://medium.com/we-are-madewithlove/does-code-need-to-be-perfect-a53f36ad7163

Read more

How to open source at Zalando

Zalando, a large online fashion plaform, published it's guidelines around open source creation and usage.

Why Open Source? Because it can: improve quality, mitigate risk, increase trust, save us money, expand our technology choices, be fun, enable us to give back to the community, strengthen our tech brand, and attract talent. ... Do “Open Source First”: If your Zalando project can also be useful to non-Zalandos, release it as open source from the start.

https://github.com/zalando/zalando-howto-open-source

Read more

Structuring PHP exceptions

Alain Schlesser wrote an article on how to manage exceptions in a large codebase.

I seem to constantly work on improving my habits regarding the use of exceptions. I think it is an area that I haven’t yet fully explored, and it is very difficult to find anything more than very basic explanations and tutorials online. While the consensus is to use exceptions, there is very little information on how to structure and manage them in a larger codebase. The larger and more complex your projects become, the more important it is to start with a proper structure to avoid expensive refactoring later on.

https://www.alainschlesser.com/structuring-php-exceptions/

In my opinion a good exception message in most cases contains three things:

  • the reason why something went wrong
  • the data that caused the problem
  • suggestions on how to solve the problem

Named constructors for exceptions are the perfect place to build up such a message. Want to learn more? Ross Tuck wrote a good blog post on the subject too.

Read more

How to refactor code with PhpStorm

Matthew Setter demonstrates PhpStorm's handy refactorings. Personally I use "extracting code to a new method" quite a lot.

Refactoring covers a range of different techniques, including moving, extracting, copying, deleting, and renaming. These cover all the types of changes which you are likely to make to your code on an ongoing basis.

Gladly, PhpStorm’s refactoring functionality, which is included as part of the core package, has support for all of these. In this tutorial, I’m going to step through a couple of them; specifically:

  • Extracting code to a new method
  • Renaming a function
  • Changing a function's signature

https://www.matthewsetter.com/refactoring-code-with-phpstorm/

Read more