REGEX 2

Okay in the previous post we had found the “find” tool and realised we can do so much more with it using regular expressions (regEx).

To recap a regEx is

“a sequence of symbols and characters expressing a string or pattern to be searched for within a longer piece of text.”

\d = a character 0 to 9

\w = any character a to Z and 0 to 9

\s =  whitespace

Example:

\d\d\d will (using the find tool in your text editor) will highlight groups of 3 numbers in a string

\w\w\w\w\w will highlight groups of 5 characters

Notice how \w\w\w included numbers and letters

\s\s will highlight double spaces

Lets look for words that have only 4 characters.

A 4 letter word can be described as,

“a space followed by any 4 characters, followed by a space”

\s\w\w\w\w\s

Which can be rewritten as

\s\w{4}\s

But that will also include numbers. To ignore numbers

\s\w{4}[a-z]\s

Not quite there, if you are playing along you will notice that we are highlighting 4 letter words and the space before and after. What we need is to set boundaries.

\b\w{4}[a-z]\b

\b is a boundary, there are a few but for now lets stay with ‘spaces’. So with that you can find all four letter words

REGEX 1

Part 1 of understanding regular expressions (regEx).

RegEx is not just useful when writing code ( across different languages they are broadly similar) but I have found knowing a bit allows me to quickly become a “power user” when using the find replace functions in text editors like VSCode and PHPStorm.

If you are using VSCode bring up the “find” box and have a look for the icon .*

So instead of just searching for a text string you can quickly scan more accurately.

PHP7 The Null Coalesce Operator

This is a simple and quick to describe, it will even save you a bunch of typing.

Before PHP 7

$name = isset($_POST['name']) ? $_POST['name']  : 'Default name';

Now with PHP 7

$name = $_POST['name'] ?? 'Default name';

Soooo much better

strpos() not working?

PHP strpos() not working as expected? It could be a  “non-strict” comparison problem.

When using strpos() to determine whether a substring exists within a string the  results can be misleading: Remember FALSE == 0?

Consider the following:

$quote = 'Dave rocks';
 
if (strpos($quote, 'Dave')) {
    echo 'Dave is awesome.';
} else {
    echo 'Dave is not awesome.';
}

strpos() Returns position is 0 ( zero ) that is evaluated as FALSE so, “Dave is not awesome”.

Much better. In this case adding the strict comparison === ( 3 equals ) to the “if” statement asks if strpos() returns a number and  is not strictly FALSE. So, “Dave is awesome”

$quote = 'Dave rocks';
 
if (strpos($quote, 'Dave') !== FALSE) {
    echo 'Dave is awesome.';
} else {
    echo 'Dave is not awesome.';
}

For more see PHP.net

 

 

 

Laravel Pagination

Pagination with Laravel (5.4 at the time of writing) is very easy.

Say you want a table of users

In your controller:

$user = User::all()->paginate(10);

In the view loop through your users as normal and then add

$user->links() where ever you feel like it and more than one place if you are feeling dandy.

There is more..

But say you want more than one paginate-able list/table on the same page? This is the paginators signature

paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)

Easy, extending the original query lets get all the threads/comments for a user. Assuming your User model can dish out Threads and Comments

$user = User::find(1);
$threads = $user->threads()->paginate(4, ['*'], 'threads');
$comments = $user->comments()->paginate(4, ['*'], 'comments');

Then in your view loop through your comments and add

$comments->links();

Loop through your threads and add

$threads->links();

 

 

 

Composer – Init, Install and update

Assuming that composer is installed on your machine what next?

If you do not have a composer.json file lets create one. In your command line ‘cd’ into your projects root folder. Then type

composer init

and answer the questions. Easy.

Look at your projects root directory and you will see a composer.json file. This is where you can add/remove packages, set namespaces, set files that are always load, run scripts, and lots of other good stuff.

Do you see a vendor/ directory? No? At this stage type

composer install

This actually ignores the .json file and reads or creates a composer.lock file then installs all the packages and dependencies required ( as well a bunch of other stuff – see the end of the post). The lock file is important when there are multiple developers/users it ensures that we/you are all using the exact same versions of installed packages.

Now lets pretend that you have cloned a project from GitHub that uses composer. You wont see a vendor/ directory but you will have a lock file.

composer install

Now you have a vendor/ directory and all is right with the world.

If you try and  run install again it won’t do anything ( try it if you want )

If you want to add packages use the

composer require name\package

If you want to update the composer files and logs

composer update

Updates your dependencies to the latest version according to composer.json, and updates the composer.lock file.

“A bunch of other stuff”

Composer can do a whole lot more. Including

  • Running scripts after installing, updating, etc
  • Autoload files. For example helper files with common functions
  • Pulling packages from GitHub. Great if you are writing your own
  • Lets you have a development environment and production sets of packages. E.g. so you can have PHPUnit just on your local machine.

Laravel Real-Time Facades (Bastards!)

Come on Taylor Ortwell whats the deal? I spend time learning about Facades and their round-a-bout method of getting them registered and running. Now with Laravel 5.4 I can get the same outcome by typing a single line of code.

WTF?

What is a  Laravel Facade?

A Facade is a “static” interface for classes that are available in the application’s service container. Think functions on steroids!

Creating them WAS simple but there where a few loops you had to jump through. But now just declare them using the Facades namespace

use Facades/{location}/{of}/DoSomething;

and use them with

DoSomething::amazing()

No need to register your Facades. Just like before DI is taken care of.

Laravel Lovelyness

In case you don’t get it I think this new method of declaring Facades is a good thing.

Laravel Validation of unique fields

Laravel Validation of unique fields e.g email

Basic server side validation in Laravel is ridiculously easy. The following inside a controller will validate the passed values and redirect back if it fails.

$this->validate($request, [

            'firstName' => 'required',

            'lastName' => 'required',

            'email' => 'required|unique:users',

            'password' => 'required|confirmed',

            ]);

You can see what fields are required; the email has to be unique in the database users table and the password is required and must match a field named ‘password_comfirm’. When this validation passes you can then add the new user.

What about UPDATING or (PUT/PATCH) the user form is returned, the firstName has changed and the email remains the same. The original validation code will not pass and return an error of ‘email already in use’.

Solution

$this->validate($request, [

            'firstName' => 'required',

            'lastName' => 'required',

            'email' => 'required|unique:users,email,'.$id.'',

            ]);

The email’s unique rule now looks up the users table, looks for the email address except where the id column matches $id

For more information: https://laravel.com/docs/5.4/validation#rule-unique

 

PHP Don’t Abbreviate

Simply put, please do not abbreviate in your code.

Always code as if the guy who ends up maintaining your code will be a
violent psychopath who knows where you live.  Code for readability. John F Wood

If others have to read it they will have no idea what an abbreviation means and when you come back to it in 6 months time will you remember what this does?

<?php
function delHisFile($p) { 
// Do something
 }

Or

function sort(array $a) {
 for ($i = 0, $c = count($a);  $i < $c;  $i++) { 
// Do something
 }
}

How does this read?

<?php
function deleteHistoryFiles($path) { 
// Do something
 }


function sort(array $array) {
 for ($index = 0, $array_count = count($array); $index < $array_count;  $index++) { 
// Do something
 }
}

When I started out coding for some reason I thought variables, functions, methods and class names that where long and descriptive would have an adverse effect on performance ( I know daft eh) .

PHP foreach() function

Okay, another everyday snippet of PHP code tweaked.

We all use the following

<?php

foreach($array as $item){

// Do something

}

?>

Which works fine, sometimes the // Do something gets complicated with HTML

<?php

foreach($array as $item){

echo '<tr>';

echo '<td>'.$item->first_name.'</td>';

echo '<td>'.$item->last_name.'</td>';

echo '<td><a href="'. $item->name .'">'.$item->email.'</a></td>';

echo '</tr>';

}

?>

After a while it gets messy and can be easy to have errors in your HTML which your editor might not pick up.

How about this for a solution – its an Alternative Form

<?php

foreach($array as $item) : ?>

<tr>

<td><?= $item->first_name ?></td>

<td><?= $item->last_name ?></td>

<td><a href="<?= $item->email ?>"><?= $item->email ?></a></td>

</tr>

<?php endforeach ?>

There are a few other ways but this reads really well. If you are looking to store the HTML as a variable before echoing it out have a look at ob_start(). However, creating chunks of HTML and passing them from place to another isn’t really good form – see separations of concerns  and MVC

 

This also works for if() statments