Toggling in Javascript, PHP and possibly other environments

For a long time if I wanted to change the state of a variable between true and false (toggling). In PHP I would do something like…

$switch = true;
if($switch == true){
    $switch = false;
}else{
    $switch = true
}

That worked fine, then there came Ternary shorthand

$switch = true;
$switch = ($switch == true ? false : true);

Not bad eh? Much easier to read. Then came this

$switch = true;
$switch = !$switch;

If you read it out loud it sounds like, ‘Switch is not true?’ So the answer would be either

True = $switch is false

Or

False = $switch is true

Javascript reminder #1 Spread syntax

Okay, a quick reminder on Spread Syntax

If you have a Javascript function that you call with

average(1, 2, 3);

function average(x, y, z){
// Average of the three numbers
}

You are limited to just three properties/arguments. Not very useful if you have more or less numbers you want to find an average. Using Spread Syntax we don’t have to worry about the number of values passed

function average(...args) {
  var sum = 0;
  for (let value of args) {
    sum += value;
  }
  return sum / args.length;
}

average(2, 3, 4, 5); // 3.5

The Spread Syntax ( the three dots{name}) includes all the unknown values.  It gets better still

var averageMethod = 'mode';
var roundTo = 2; /Decimal places
doThing( averageMethod, [2,4,3,6,10,19], roundTo);

function doThing(method, ...valuesToAverage, roundTo)
{
// Calculate averages
}

And Spread Syntax can be used when creating arrays

var parts = ['shoulders', 'knees']; 
var lyrics = ['head', ...parts, 'and', 'toes']; 
// ["head", "shoulders", "knees", "and", "toes"]

Good eh?

 

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

MY .bash_profile for Laravel

I’ve only started using my .bash_profile a couple of years ago. To be honest I look back now and think, ‘What a plonker, you should have been using since day one’

Why? If you are even a little bit lazy it can save you loads of typing. If you are not lazy it can help you get more done in less time.

For example. Instead of typing

php artisan tinker

I can type

tinker

Still not convinced? How about opening the Apache error log, scroll to the last entry and then automatically scroll down when a new error has been reported?

This

tail -f /usr/local/var/log/apache2/error_log | sed "s/\\\n/^M^L/g"

Becomes this

apachelog

Here is my Lavavel and Lithium .bash_profile, it is not my complete profile but is enough to give you a taste.

#List all including .hidden files

alias ll='ls -la'

#Apache log 

alias apachelog='tail -f /usr/local/var/log/apache2/error_log | sed "s/\\\n/^M^L/g"'

#alias apachelog='tail -f /usr/local/var/log/apache2/error_log | sed "s/\\\n/" | sed "s/\\\n/^M^L/g"'

#PHPSpec

alias phpspec='vendor/bin/phpspec'

#Apache http.conf

alias apacheconfig='open -e /usr/local/etc/apache2/2.4/httpd.conf'

#Apache status

alais apachestatus='ps -aef | grep httpd'

export PATH=/usr/local/bin:/usr/local/sbin:$PATH

export PATH="~/.composer/vendor/bin:$PATH"

#PHP Artisan

alias art='php artisan'

#Laravel PHP  artisan tinker

alias tinker='php artisan tinker'

#Lithium Terminal/console

alias li3='libraries/lithium/console/li3'

#Start Apache and MySQL

function startme(){

        sudo apachectl -k restart

        mysql.sever start

        pwd 

} 

PHP for loop

The PHP ‘for loop’ based on my experience is an underused PHP function. We all have seen the following…

<?php
$array = [  ];// Of things

for($i=1; $i <= count($array); $i++)
{
// Do something 
}
?>

This is what happens

  1. Initialise the loop with the variable $i set to 1
  2. Count how many items are in the array and compare with $i to see if it greater or less
  3. Do something
  4. Add 1 (increment) to $i
  5. Count how many items are in the array and compare with $i to see if it greater or less
  6. Do something
  7. Add 1 (increment) to $i

Repeat

And this works fine. Lets look at the structure of the ‘for loop’ and see what is happening.

The For Loop Structure

for( {exp1}; {exp2}; {exp3} )
{
//Do something
}
  • Exp1 will be run once only and at the first time around the loop ( AKA an iteration)
  • Exp2 Will run at the beginning of every iteration ( or go around the loop)
  • Exp3 Will run at the end of every iteration.

In the original  code if the array is large it can have a negative impact on performance. Can it be made better?

Yes. How about the following?

<?php
$array = [  ];// Of things
$array_count = count($array);
for($i=1; $i <= $array_count; $i++)
{
// Do something 
}
?>

This works much better. The array is only counted once, but in my opinion it does not read well and feels clunky. What can be done?

The ‘for loop’ has 3 blocks (exp1, exp2, exp3) each separated with a colon. What you put in these blocks is upto you, you can even leave them blank. That being said lets rewrite the original code so that

  1. It works as expected
  2. It does so efficiently
  3. When you read it, it makes clearer sense;
<?php
$array = [  ];// Of things
for($i=1, $array_count = count($array); $i <= $array_count; $i++)
{
// Do something 
}
?>

Is that not better?

See PHP.net for more