data codes through eyeglasses

Log Laravel Eloquent SQL queries with parameter values

Frequently I find the need to see what SQL queries are actually generated magically by Eloquent. It really helps when I need to debug a query or figure out why its not performing well. Since I keep referring back to this very useful code snippet I thought its good to keep it here so its readily available for myself and anyone else. Add the following code in the boot() method of AppServiceProvider.php:

    public function boot() {
if (\App::environment('local')) {
DB::listen(
static fn($query) => logger(
Str::replaceArray('?', array_map(fn($binding) => '\'' . $binding . '\'', $query->bindings),
$query->sql
)
)
);
}
}

If you haven’t changed Laravel’s default logging configuration all queries executed will be logged in storage/logs/laravel.log. The full query including its parameter values will be included which makes it dead easy to then copy/paste and run EXPLAIN so you can see how you could optimize it. Note that this will only execute if APP_ENV is set to local so no sensitive information will be logged on your production logs.

PHP 7.3 is out

Can be downloaded here http://php.net/releases/7_3_0.php

I personally would stick to 7.2 for now at least until the first point releases of 7.3 are out just to be on the safe side.

To install on Ubuntu 18.04:

sudo add-apt-repository ppa:ondrej/php
sudo apt-get update

deb http://ppa.launchpad.net/ondrej/php/ubuntu bionic main 
deb-src http://ppa.launchpad.net/ondrej/php/ubuntu bionic main

sudo apt-get install php7.3

Xdebug is also available but its currently under beta. Since you won’t be using that in production it doesn’t hurt to try.

JPHP – Compile PHP directly to JVM (Java) Bytecode

I stumbled upon the JPHP project today which adds yet another direction to the PHP world. JPHP is an one man project by Dmitriy Zayceff who’s been working on it for the past 2 years and I must admit he must have spent a lot of time on it. Here’s some key points:

  • Compile PHP code into Java Virtual Machine bytecode (into JAVa’s .class files)
  • Use the standard PHP function library including some extensions.
  • Can use any JAVA class through PHP code (you need to write a wrapper for it but it works)
  • Create cross platform GUI or CLI applications
  • Develop Android apps in PHP
  • It executes faster than the current PHP branch and even faster than PHP7.
  • Allows for both stateful and stateless execution when used as a Web scripting language (i.e. you can either choose to execute as a long-running process with shared memory or reset with every request like standard PHP.
  • Can do just in time compilation of PHP files.

Project’s Github page.

Benchmarks can be found here. Page is in Japanese but all you need to look at is the two tables. The first shows the time taken for the 1st run of the benchmarks and the next run where the code is already pre-compiled and JPHP wins.

Recent & Worthwhile in Web Development

PHP

  • Remember Me – Safely Secure Long Term Authentication Strategies
    A detailed explanation on how to implement the Sign in ‘Remember Me’ functionality securely in PHP (the concepts are the same for every language). I must admit I never considered timing attacks for the authentication token until I read this.
  • Laravel 5.0 was released
    The 5th installment of one of the most popular PHP MVC and all-around frameworks was released. Wrote a summary of the changes in another post.
  • HHVM 3.5.0 Released
    The Facebook supported alternative PHP VM has a new version.
  • Cockpit
    A plug-n-play CMS for PHP sites. Targeted to developers, who built web apps and don’t want to re-invent the wheel every time for the content parts of their app. Uses SQLlite or MongoDB as data store.
  • Return Types Declarations approved for PHP7
    In PHP7 we’ll be able to declare the return type for functions and will be enforced causing a fatal error if a different type is returned.  Here’s an example of how it will look taken straight from the RFC:
    [pastacode lang=”php” message=”” highlight=”” provider=”manual”]

    function foo(): array {
      return [];
    }

    [/pastacode]

JS /HTML / CSS

  • ReactJS for Stupid People
    A good introduction on what Facebook’s ReactJS is about and why you should use it.
  • Animated Bezier Curves
    Demonstration of how parametric Bezier curves are constructed. Uses D3, and the code is straight forward, just View Source.
  • Konva JS
    Object-oriented 2D HTML5 Canvas Framework. Event driven, layer support, drag and drop, shape nesting, animation and all the usual bells and whistles.
  • mProgress.js
    Material Design style animated progress bar. Uses CSS3, has no other library dependencies and has beyond the ordinary features such as indeterminate progress (7.7kb minified JS).
  • RubaXa Sortable
    Minimal & customizable Sortable with touch support and no dependencies.
  • fieldVal
    Programmatic Javascript Field Validation library (runs both on browser and server). Includes an optional UI library for presenting validation errors in forms.
  • TauCharts
    Javascript charting library which aims to be flexible rather than offering pre-packaged chart setups.

PHP: array_walk vs foreach

Its a minor optimization but might make a difference if you process large arrays. Built-in PHP function array_walk allows you to apply a function to every element in an array. Obviously you can get the same results using a foreach. One would expect the built-in function to be faster since its written in C and hopefully has been highly optimized but it turns out, that’s not the case. After a bit of online research and some tests, foreach is the clear winner. Here’s the examples:

[pastacode lang=”php” message=”Using foreach – 0.01022s” highlight=”” provider=”manual”]

<?php
$test = array_fill(0, 10000, 'test_data');
$start = microtime(true);

foreach ($test as $key => $value)
{
    $result[$key] = 'testdata';
}

$end = microtime(true);
$time = $end - $start;
printf( "%0.5fs", $time );

[/pastacode]

[pastacode lang=”php” message=”Using array_walk – 0.08700s” highlight=”” provider=”manual”]

<?php
$test = array_fill(0, 10000, 'test_data');
$start = microtime(true);

array_walk($test, function($value, $index)
{
    $value = 'testdata';
});

$end = microtime(true);
$time = $end - $start;
printf( "%0.5fs", $time );

[/pastacode]

foreach wins. Case closed.

Laravel 5.0 Final released

  • New project directory structure – now looks more intuitive.
  • Now more components implement interfaces for better extensibility.
  • Route Caching for faster performance.
  • Middleware support for routes.
  • Common Authentication functionality out of the box (controllers for authentication, registration, forgot password and their respective views are all included).
  • Job Scheduler so you only need to run one cron job and the scheduler picks what to run from the queued jobs for you.
  • and more…

Have a look at the release notes.

How to enable WordPress Debug Mode in 60 seconds

If you are a WordPress developer or if you just installed a misbehaving plugin you will need to enable WordPress’s debug mode in order to figure out what made your site get into the dreaded blank white page (unlike Windows WordPress has a White-Screen-Of-Death). So here’s the quick step-by-step guide to get you going:

Step by Step

  1. Connect via FTP to your site (use FileZilla which is free, if you don’t have an FTP client already installed) or just open your text editor if you are running local.  (15 seconds)
  2. Browse to WordPress home directory, and open wp-config.php for editing. (10 seconds)
  3. Hit Ctrl-Endor scroll to the bottom of the document, locate the line that says define(‘WP_DEBUG’, false);  – you can find it a few lines before the end of the file. (15 seconds)
  4. Change false to true and Save. (15 seconds)
  5. Refresh the page and you should be able to see the errors.  (5 seconds)

 

Total: 60 seconds.

 

Its recommended you don’t run this option on a live production site but if you really must, make sure you turn if back off when you are done. Alternatively you can enable the debug log to be sent to a file instead of the browser by also adding the following line in your config file:

define(‘WP_DEBUG_LOG’, true);

This will cause the error messages to be saved in a file called debug.log in the wp-content sub-folder of your installation. Again make sure this file is protected because by default anyone from the web can access it in the particular folder.

 

And if my instructions are not detailed enough you can look at the long version on the WordPress codex.

PhpStorm – an IDE worth its name

I recently switched to JetBrains PhpStorm as my main IDE for PHP/HTML/JS/CSS development. I tried many solutions in the past such as Dreamweaver (please don’t try it), NetBeans, Aptana, Eclipse PDT, before settling with Zend Studio for quite sometime and finally a couple of months ago I gave ZendStudio the boot and switched to PhpStorm. I am currently using version 6.0 from the Early Access Program (the current stable is version 5) – and I am planning to buy it once 6.0 final is out. Read More