This guide assumes that you have php cli installed and you have php version > 7.

To check your PHP version:

⚡ php -v
PHP 7.1.1 (cli) (built: Feb 13 2017 10:05:49) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.1.1, Copyright (c) 1999-2017, by Zend Technologies
    with Xdebug v2.5.0, Copyright (c) 2002-2016, by Derick Rethans

Installation

cd /tmp

wget https://github.com/phpredis/phpredis/a
rchive/php7.zip -O phpredis.zip

unzip -o /tmp/phpredis.zip && mv /tmp/phpredis-* /tmp/phpredis && cd /tmp/phpredis && phpize && ./configure && make && sudo make install

Now check your php.ini location using the command:

⚡ php -i | grep php.ini

you’ll get output like:

/your/path/to/php.ini

run the following command:

sudo echo "extension=redis.so" >> /your/path/to/php.ini

To check if you have redis extension loaded, run the command:

⚡ php -i | grep Redis
Redis Support => enabled
Redis Version => 3.0.0-rc1

In twig, you can add filter json_encode which internally is using json_encode php function.

http://twig.sensiolabs.org/doc/2.x/filters/json_encode.html

Now to add options just like json_encode in php,


{{ data | json_encode(constant('JSON_HEX_APOS')) | raw }}

to add more than one option you can use b-or operation to have multiple json_encode options:


{{ pageData|json_encode(constant('JSON_HEX_APOS') b-or constant('JSON_HEX_QUOT') ) | raw }}

php elephant 7.1

So I ran into an issue today while debugging a json string which is being produced from serialising an object. The float values had more decimal points than the ones in the object.

For example, consider the following code:

<?php

class MyFloatClass implements \JsonSerializable
{

    /**
     * @var float
     */
    public $value1;

    /**
     * @var float
     */
    public $value2;

    /**
     * myFloatClass constructor.
     * @param float $value1
     * @param float $value2
     */
    public function __construct($value1, $value2)
    {
        $this->value1 = $value1;
        $this->value2 = $value2;
    }

    function jsonSerialize()
    {
        return [
            'value1' => $this->value1,
            'value2' => $this->value2,
        ];
    }
}

$myObject = new MyFloatClass(12.23, 43.99);

echo json_encode($myObject->jsonSerialize());

Running the code above in PHP 7 will give the following output:

{"value1":12.23,"value2":43.99}

If you run the code in PHP 7.1 and you have serialize_precision not equal to -1, it will give totally different output.
Example, consider the following setting:

<?php

ini_set('precision', 14);
ini_set('serialize_precision', 17);


class MyFloatClass implements \JsonSerializable
{

    /**
     * @var float
     */
    public $value1;

    /**
     * @var float
     */
    public $value2;

    /**
     * myFloatClass constructor.
     * @param float $value1
     * @param float $value2
     */
    public function __construct($value1, $value2)
    {
        $this->value1 = $value1;
        $this->value2 = $value2;
    }

    function jsonSerialize()
    {
        return [
            'value1' => $this->value1,
            'value2' => $this->value2,
        ];
    }
}

$myObject = new MyFloatClass(12.23, 43.99);

echo json_encode($myObject->jsonSerialize());

output will be:

{"value1":12.23,"value2":43.990000000000002}

So first thing to check when having PHP 7.1 in your prod environment or even development environment is to check that you have default values for:

precision => 14
serialize_precision => -1

You can check that using CLI by running the following command:

php -i | grep precise

More reading: PHP Wiki – Precise Float Value

Photo Credit PHP Elephant with Christmas Tree Bokeh

Do you know that in symfony cli you can use shortcuts? you only need to write the first letter of the command and this will run perfectly.

Example:

php app/console cache:clear

You can use:

php app/console c:c

Same with doctrine commands:

php app/console doctrine:database:create
php app/console doctrine:database:drop   

can be

php app/console d:d:c
php app/console d:d:d   

Enjoy!

Database Table inheritance in Doctrine

Have you came across a situation when you need to apply Object Oriented Inheritance principle in database design? Did you have two tables sharing some fields and you wanted to connect them together without having to run queries or parallel insertion? Search no more as Doctrine supports this using Class Inheritance with discriminatorMap.

At the end of this post, you’ll learn how to create a product table (super class) and 3 different product category tables (furniture, food, online downloadable items) that inherent product table so when you insert a new furniture item, it will save same id, price to product table as well.

Continue reading

Fixing Warning: date_default_timezone_get(): It is not safe to rely on the system's timezone settings on Mac

If you run the following command:

php -i | grep 'Configuration File'

you will receive:

Loaded Configuration File => (none)

This is causing error of unspecified timezone or error:

Warning: date_default_timezone_get(): It is not safe to rely on the system’s timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function.

To fix it, simply copy the php.ini.default in /etc

cp /etc/php.ini.default /etc/php.ini

sudo vim /etc/php.ini

search for timezone you’ll find a commented line:

[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
;date.timezone =

Uncomment it and assign your timezone, example:

[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = Europe/London

PHPStorm

Useful shortcuts

Shift ⌘O spotlight like to get files

⌘O Find file by ClassName

⌘E Navigate to recent files

⌘L Go to specific line

⌘B Go to declaration of variable

How to auto style PHP code to follow PSR1/PSR2

1) Go to Preferences.

2) Search for Code Style

3) Choose PHP

4) Click on Set From..

5) Choose PSR1/PSR2 as show below:

phpstorm-psr1_psr2

Doctrine load fixtures – How to load particular fixture

Symfony has an option to load fixtures from command line:

$ php app/console doctrine:fixtures:load --help
Usage:
 doctrine:fixtures:load [--fixtures[="..."]] [--append] [--em="..."] [--purge-with-truncate]

Options:
 --fixtures             The directory or file to load data fixtures from. (multiple values allowed)
 --append               Append the data fixtures instead of deleting all data from the database first.
 --em                   The entity manager to use for this command.
 --purge-with-truncate  Purge data by using a database-level TRUNCATE statement
 --help (-h)            Display this help message.
 --quiet (-q)           Do not output any message.
 --verbose (-v|vv|vvv)  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug.
 --version (-V)         Display this application version.
 --ansi                 Force ANSI output.
 --no-ansi              Disable ANSI output.
 --no-interaction (-n)  Do not ask any interactive question.
 --shell (-s)           Launch the shell.
 --process-isolation    Launch commands from shell as a separate process.
 --env (-e)             The Environment name. (default: "test")
 --no-debug             Switches off debug mode.

But if you assign the full path to fixture file with --fixtures option, its not going to load it and you’ll end up with error:

[InvalidArgumentException]
Could not find any fixtures to load in:
– full/path/to/file.php

The other option is to load the folder itself by typing the full path to folder where fixture file resides.

php app/console doctrine:fixtures:load --fixture=/src/BundleName/DataFixtures/ORM/