Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

aurawindsurfing's avatar

DRY in php?

I remember when I was learning ruby there was a DRY rule used everywhere (Do not Repeat Yourself).

Are traits in php the only similat thing or is there some other way thal will allow me reuse pieces of my code. I mean not even a function but a piece of a funtion maybe?

Cheers!

0 likes
6 replies
christianyeah's avatar

in Laravel projects, I will put these shared function to traits. Or you can create your own package.

aurawindsurfing's avatar

Ok so what tou say is to create a Trait with all the junk small functions that I need and then to import that to my controllers.

But is there a way for even like code snippets? Lets say I search a model in few places in my code and the only difference is that sometimes search results are paginated some are a take(20) and some are get() but the proceedeing params are always the same.

Can I DRY this somehow?

I understand Trait and function gut I can not really chain those to have different end params.

If I create a function at the model I think the same problem will arise?

Cheers

topvillas's avatar

Eloquent already has a chaining API that passes through a query builder. But you might so something like this ...

function searchEmails($email) {
    return User::where('email', 'LIKE', "%{$email}%");
}
$searchEmails('gmail')->paginate();
$searchEmails('gmail')->take(20);

This might not work as I just got up and haven't had my coffee yet. But I think the idea is sound.

aurawindsurfing's avatar

Imagine what you can do with coffee!

Cheers will refactor and give it a shot!

tykus's avatar
tykus
Best Answer
Level 104

I prefer query scopes for this:

function scopeSearchEmails($query, $email)
{
    return $query->where('email', 'LIKE', "%{$email}%");
}

You get the benefit of context along with reuse and the ability to continue chaining.

User::searchEmails('gmail')->paginate();
User::searchEmails('gmail')->latest()->take(20);

You can also create scopes which combine your custom scopes if that makes sense for your app.

Chrizzmeister's avatar

This question is a bit vague. DRY is not something ruby specific it is just a good way to program in general. DRY should always be the end goal. Since you are asking this question on laracasts here are some php/laravel related examples:

  • traits
  • parent/child classes
  • partials for views
  • components for views
  • extracting classes for a piece of functionality
  • extracting common tasks to dedicated classes
  • making a repository to bundle code
  • make a global helpers file for general helper function
  • all design patterns
  • ..

its pretty much endless , so you need to be more specific and show an example of what piece of code you would like to make dry.

2 likes

Please or to participate in this conversation.