Rules to Reuse Laravel Code Like a Pro
Tags: laravel, code
Published: 2023-11-02 15:25:00

Hey everyone, Isra here! I'm excited to share my tips for making reusable code.

When I first started coding, I would write big messy programs that I couldn't change later. Yuck! Then I learned to break my code into smaller pieces that could be used over and over. 

The other day, a client wanted help with their website. After using some reusable code, they finished way faster! They were so happy that they said, We need to [hire Laravel Developers in Seattle](https://hybridwebagency.com/seattle-wa/hire-laravel-developers/).

Now I want to teach you how to make your own reusable code. There are easy ways to share functions and classes between programs. We'll look at traits, interfaces and packages too. 

Turning your code into building blocks is fun. Other people can use the blocks in their programs too! Who knows, maybe clients will want to hire you in Seattle after seeing your reusable code skills.

Let's get started! I'll show you my best techniques. By the end, you'll be an expert at reusable code like me. I'm excited for you to start sharing your code and helping more people.


## Extract Logic into Reusable Classes

Let's talk about taking parts of your code and putting them into classes! This is so useful when you find yourself writing the same things over and over.

### Examples of common reusable classes 

For example, say you always validate user data the same way. You could make a UserValidator class with methods like validateName(). 

```php
class UserValidator {
  public function validateName($name) {
    // validation logic
  }
}
```

Another idea is a Mapper class that changes data from one format to another.

### Guidelines for designing reusable classes

When making reusable classes, keep them focused on one thing. The validator class is just for validation. 

Also make sure the classes don't rely on things outside itself. The validator shouldn't care where the data comes from.

Try to plan for how others may use your class too. Add descriptive names and comments to your code.

Reusable classes help DRY up your code (Don't Repeat Yourself). Just include the class and call the methods you need.

## Use Traits for Common Behaviors

Traits are really handy for putting together bits of code that you want to include in different classes. 

### Examples of reusable traits

A common trait is SoftDeletes, which adds "deleted_at" and scopes to check for deleted objects.

```php
trait SoftDeletes {

  public function scopeWithTrashed($query) {
    return $query->withTrashed();
  }

  // other deletion methods
}
```

### Creating well-designed traits

When making traits, keep them focused on one behavior. SoftDeletes should only deal with deleting/restoring.

Avoid hard dependencies and external data in your traits. They should work anywhere they are used. 

Add documentation so others understand the trait's purpose and how to use it correctly.

Traits are great for modeling cross-cutting concerns like timestamps, slugs, or other repetitive tasks. Keep your classes light by moving shared logic into reusable traits!


## Bundle Logic into Packages

When you have a lot of reusable code, it's time to package it up!

### When to create packages

If you find yourself including the same files in multiple projects, that's a sign it's package material. Anything others could download and use too.

### Folder structure and namespaces 

Packages generally follow a simple folder structure and namespaces so they are easy to use. Having a good readme helps explain how to install and use it.

### Using existing packages as references

Check out popular open source packages like [Laravel packages](https://laravel.com/docs/10.x/packages) or others on Packagist. You can see examples of code organization, documentation and distribution that help users adopt it smoothly.

Packaging your code keeps it organized and lets you share that usefulness with the whole community. Others can simply install it with Composer and get your reusable magic!


## Leverage Laravel Components

Laravel already gives us amazing tools to build on!

### Core Laravel components

Some major ones are Eloquent for databases, Collections for arrays, and Blades for views. These were made to be extended. 

### Building on core components

For example, you could build a JSON API by adding methods to the Eloquent Model class. Or extend Blade with custom directives for your templates.

Collections are so useful - you'll find yourself wanting to add reusable methods there too.

The framework does the heavy lifting so focus on your custom logic. Leverage the solid foundations Laravel provides to easily create reusable solutions.


## Distribute with Composer

Once your package is ready, Composer makes it easy to share!

### Introduction to Composer 

Composer manages PHP dependencies. To use a package, you just add it to your composer.json file.

```json
"require": {
  "vendor/package": "^1.0"
}
```

### Publishing packages to Packagist

Upload your package to [Packagist](https://packagist.org) so anyone can find it with a search. 

### Including packages in projects

From the project folder, run `composer install` to download. Then in PHP use:

```php
require_once 'vendor/autoload.php';

$class = new Vendor\Package\Class;
```

With Composer, your packages can be used by anyone with a single command. Distribute that reusable goodness far and wide!


Here are the interfaces sections with code examples:

## Standardize Contracts with Interfaces

Interfaces provide a common contract for classes to follow.

### Benefits of interfaces

They allow classes to be interchangeable if they follow the same interface. Great for testing too.

### Common interface examples

A CrudInterface could mandate find/create/update methods:

```php
interface CrudInterface {

  public function find(int $id);

  public function create(array $data);

  public function update(int $id, array $data);

}
```

A ModelInterface may expect properties like $table and relations: 

```php 
interface ModelInterface {

  public function getTable();

  public function relations();

}
```

Interfaces ensure classes work the same way even if internal logic varies. They let code depend on standardized behaviors.

Contracts promote code consistency, testability and reuse across applications. Define expected class APIs with interfaces!


## Conclusion

Writing reusable code has really improved my craft as a developer. It used to be that I would just build one-off scripts and functions without much thought for how others could leverage my work. But since learning techniques like extracting logic, using interfaces and publishing packages, I've found so much more satisfaction in my code.

Nothing fills me with more pride than hearing how a package I created helped someone else complete a project faster or build something really cool. And it's rewarding to maintain reusable code over time, adding new features and keeping it useful for an ever-growing audience. More than that, focusing on reusability has made me a better problem solver. I understand code organization and design patterns at a deeper level now.

Most of all, producing reusable code that spreads value to others has uncovered for me the true joy of this profession. While the work itself can be challenging at times, remembering why we do it makes all the difference. I'm thrilled to be part of uplifting the developer community in this small way, and I hope sharing these lessons proves equally helpful for your journey too.