by Tom Millard

Referencing Laravel 5 illuminate packages in Lumen

laravel - lumen

This was strangely confusing for me, I went straight from Laravel 4, which might explain the problem.

I need to use Lumen for a lightweight project i was doing for a client, the whole Laravel framework seemed a bit overkill.

All i needed was 'Files' support in one of my Seeders, it turned out to be a bit of an ordeal. However looking back it was obvious, I just needed to include the namespace.

In order to use 'file' you would do something like this

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\File;
use App\Models\Files;

class FileSeeder extends Seeder {

    public function run()
    {
      File::allFiles([directory]);
    }

}

This then gives you access to that namespace.

You can also include it globally using 'class_alias' and adding it to your bootstrap/app.php file.

or you can use it like this

App\Models\Files\File::allFiles([directory]);

We can apply this method to any of the available libraries under 'vendor/illuminate/*'

by Tom Millard

Base64 Encode Images in php

php - html-2

A simple function which will allow you to base64 encode images on the fly.

    function getBase64Image($imgPath){
        $imgType    = end(explode(".", trim($imgPath)));
        $imgType    = strtolower($imgType);
        $img        = file_get_contents($imgPath);
        $img        = base64_encode($img);

        return "data:image/$imgType;base64,$img";
    }
<img src="<?php echo getBase64Image('./mini.jpg') ?>" alt="">

Why would I want to do this? simply put by doing this the browser has to make one less network connection. Which in tern will speed up your website.

...However
On Mobile, Data URIs are 6x Slower than Source Linking (New Research)

by Tom Millard

Using Traits in Laravel

php - laravel

Traits are essentially includes for your classes (I'm sure someone will correct me on that).

In Laravel I find them very useful for sharing functions/variables/etc between controllers.

For example string manipulation functions, which need to be shared across various controllers.

Mapping traits

First we need to tell Laravel about the existence of traits. Start by including the traits folder in the "autoload" part of the composer.json file.

    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php",
            "app/traits"
        ]
    },

In this layout the traits folder is in the app file, but it can be wherever you like or named anything. As long as this path matches up.

Traits Syntax

After this create a new file in your traits folder, so for me I created Strings.php

<?php
    trait Strings {

        private function clean($string) {
           return preg_replace("/[^ \w]+/", '', $string);
        }

    }

Name the trait the same as the file.

After saving this we need to run composer dump-autoload

Hooking it all up

Now that we have a trait and laravel is aware of its existence we simply use the following command under the class declaration, in any controlled we wish to include the trait.

use Strings;

and now we have access to the '$this->clean([string])' function.


Thanks to Alex Hollyman 👍

by Tom Millard

Git: Add, Commit and Push in One Command

bash - git

A simple bash command to add all current changed files, commit them, then push them up to your designated git service.

function gitCommit(){
        git add . -A && git commit -m "$1" && git push
}

We pass in one command which is the commit message:

$ gitCommit "loving it #yolo"

Simply add this function to your .bash_profile and its active on new bash sessions.

by Tom Millard

Youtube Responsive shiv for CMS Driven Content

javascript - youtube

Edits have been made to the repo code found here

When a user adds a youtube video to the site using a WYSIWYG editor the initial code output will not be responsive unless the user appends the needed element manually.

This shiv allows the user to copy and paste the video into a WYSIWYG from youtube and forget about all the responsive woes.

        .youtube-video {
            max-width: 640px;
        }

        .youtube-video__container {
            position: relative;
            padding-bottom: 56.25%;
            padding-top: 30px; height: 0; overflow: hidden;
        }

        .youtube-video__container iframe,
        .youtube-video__container object,
        .youtube-video__container embed {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
    <script>
        //requires jquery
        function youtube(){
            var t = this
            ,   node = $("iframe[src^='https://www.youtube.com']")
            ;

            function init(){
                build();
            }

            function build(){
                for(var x = 0, xl = node.length; x<xl; ++x){
                    var h = template(node[x])
                    ,   i = $(node[x]);
                    i.hide();
                    i.after(h);
                    i.remove();
                }
            }

            function template(iframe){
                var html = '<div class="youtube-video"><div class="youtube-video__container">'+ iframe.outerHTML +'</div></div>';
                return html;
            }
            init();
        }

        new youtube();
    </script>

Code on github

by Tom Millard

Editing the Host File on Mac using the Terminal

bash - hosting - unix

If you need to quickly override your internal rooting table in order to test out a site you just moved over to a new domain name, or put live and the TTL on the domain is slow you can edit the host file and point the domain name to the server ip address. Which will stop your machine looking up the ip address outside of your Mac.

$ sudo nano /private/etc/hosts

Then we can add lines to this file

[IP address]   [domain name]

Then save and exit.

by Tom Millard

Bulk Rename Images with Bash

Recently I had to bulk rename some jpg's from a horrible naming convention to something a bit more user friendly.

I wanted them to be formatted like this,

[string]-[integer].jpg

With the following bash command this was possible using a for loop

j=0; for file in *.jpg; do ((j++)) && mv "$file" "name-space-$j.jpg";  done

This piece of code does the following

  • Integrates over all the files (in this case jpg)
  • Increase the number variable by 1, j++
  • Then moves the file into a new name with our prefix and the integer

Now i have a loa of files with the following name name-space-0.jpg etc

(Warning: Always backup files if your pissing around for the first time with the terminal)

Also see Mass Move (mmv)

by Tom Millard

Get Facebook like information with php and fql

php - fql

Social media share and like counters always look a bit awkward on websites and normally allow very little change when it comes to appearance.

About 2-3 years ago I wrote a little plugin for expression engine which used various social media feed to count and display likes/shares/tweets etc

The code is a bit out of date now but might be of some use Github/share-counters.

Taking this code I formatted the response to JSON then en-coded the result to give us an object we can use.

function getFacebookLikeInfo($url){
    $url = "
        https://api.facebook.com/method/fql.query?query=SELECT%20like_count,%20total_count,%20share_count,%20click_count%20from%20link_stat%20WHERE%20url=%22$url%22&format=json
        ";

    $json = file_get_contents($url);

    return json_decode($json);
}

print_r(getFacebookLikeInfo("www.google.com"));

Which gives us

Array
(
    [0] => stdClass Object
        (
            [like_count] => 3137662
            [total_count] => 12094803
            [share_count] => 6994340
            [click_count] => 265614
        )

)
by Tom Millard

Web tools I picked up at Smashing conference Oxford

Probably worth getting these written up and put on the internet before I loose my notes, so in no order - a quick list of tools I picked up at smashing conference Oxford.

And we are done.

by Tom Millard

Javascript: Binding events by class name

javascript

Adding event listeners to elements with class names in javascript without the use of jQuery or onClick, by using addEventListener and getElementsByClassName.

By using these two functions in conjunction with each other we can assign a global action to an element with a class name declared.

    <a href="" class="button">btn 1</a><br />
    <a href="" class="button">btn 2</a><br />
    <a href="" class="button">btn 3</a><br />
    <script>
        (function(){
            var button = document.getElementsByClassName("button");

            for(var x = 0, xl = button.length; x<xl; ++x){
                button[x].addEventListener("click", myAction);
            }

            function myAction(e){
                e.preventDefault();
                console.log(e);
            }
        })(document);
    </script>

(Note: we can assign variouse event types in the same way https://developer.mozilla.org/en-US/docs/Web/API/Event/type)