DerekMartin.ca

I'm a father, manager, programmer, scrum master, geek, & movie lover.

Coding Style, Smells, & Tips

This is more obvious when creating APIs, but it’s true of all code: Code is an interface. It’s what we interact with to do our jobs. Write code for humans, and let the compiler figure out how to make it fast (or go back and make it faster after it’s working — but always, ALWAYS keep it easy to read & understand!).

The PHP community uses the PSR-1 & PSR-2 coding standards. You can tell PHPStorm to auto-format your code according to those standards. Also, re-read the Laravel Documentation whenever a new version comes out. That’s simple. What follows is a bit more nuanced.

Comments

Annotations

Naming

.

api->apiRequest()

vs

api->request()

or

Customer.php->getPaymentGatewayCustomer()

vs

Customer.php->get()

Namespaces

Put the namespace in a use statement to reduce visual clutter in the code:

$details = \App\Models\UserBillingDetails::where(...)

vs

use App\Models\UserBillingDetails;
...
$details = UserBillingDetails::where(...)

If you want a more specific name than the class name, rename the class, or alias it:

use App\Models\UserBillingDetails as UserBillingDetailsModel;

Objects

Before:

if(empty($object))

After:

if($object->isEmpty())

Before:

$this->membership['expires'] = date('Y-m-d', $event->data->object->current_period_end);
$subscription->sendFail($this->membership, $source);

After:

$membership->expire();

Before:

function methodName(Account $account){
    $card = $account->getCard();
    return $card->getTotal();
}

After:

function methodName(Card $card){
    return $card->getTotal();   
}

Constructors

Production:

$cart = new Cart(new RedisStore());

Testing:

$cart = new Cart(new ArrayStore());

Methods & Functions

The function shouldn’t need to know about the structure of data outside itself. Instead, make those values specific parameters. It’s less error-prone, easier to follow, and allows your IDE to auto-complete.

function name(Account $account){ 
    $card = $account->getCard();    
}

vs

function name(Card $card){ 
    ...
}   

Static Methods

Controllers

Before:

$setting = \App\Models\GatewaySetting::where('site', $source)->first();
$base_uri = $setting->value;

After:

GatewaySetting->getBaseUrl($source);

Models

Sessions

Traits

Views

Miscellaneous

.

$yourCollection = collect($yourArray);