Dynamically configure symfony service ID using parameters

If you like in his Depnedency configuration of injection (services.yml) the service injections make dynamically configurable wants about the parameters.yml,

parameters:
    my_class: 'App\MyClass'

can you do this using the Symfony expression language component do:

composer require symfony/expression-language

Then you can define in the services.yml:

services:
    App\Command\MyCommand:
      arguments:
        - '@=service(parameter("my_class"))'

Windows composer update fatal error: Allowed memory size of 1610612736 bytes exhausted

My composer despite unlimited storage has the following error message:

 composer update
 Loading composer repositories with package information
 Updating dependencies (including require-dev)

 VirtualAlloc() failed: [0x00000008] Zur Verarbeitung dieses Befehls sind nicht gen
 VirtualAlloc() failed: [0x00000008] Zur Verarbeitung dieses Befehls sind nicht gen

 Fatal error: Out of memory (allocated 1260388352) (tried to allocate 201326600 bytes) in phar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/DependencyResolver/RuleSet.php on line 83

If you can no longer perform a composer update under Windows, Although it has the memory limit to unlimited, then you have a problem:

The Windows Xammp is only as 32 bit system available and RAM can provide only 2 GB at the moment, a further increase is not possible.

The solution is to run composer with a 64-bit PHP on the console (This then has up to 4 GB memory).

  • Download PHP x 64 version
  • unzip it and creating a php.ini (the umbennnen php.ini-development)
  • increase memory limit in php.ini: memory_limit =. -1
  • run on the console:
"C:\php-7.2.12-nts-Win32-VC15-x64\php" C:\ProgramData\ComposerSetup\bin\composer.phar update

Yii2 versus symfony 4 – a framework comparison

I have long worked with Yii and the symfony framework and want to try the following to explain the differences between the two frameworks from programmers point of view.

Configuration of environments

When you create Web applications is typically at least 2 Environments: The development environment, on which you want to see errors and the live environment, where this should happen. To come test environment to run automated tests and perhaps a staging environment.

Symfony raises the very skillfully, with the .env files and own folders within the configuration folder.

At Yii must the programmers themselves lend a hand, to load the correct configuration, There are only from home 3 (dev, Prod, test) Vorgsehen environments, then it is confusing. more…

PHP encode string for extended ASCII 8 bit 255 Sign

To represent also umlauts in a bit, can you get the extended ASCII character set use with 255 Sign, It contains also umlauts like ä, ö, ü and ß.

In order to use this, can I use the following function:

/**
 * @param string $string
 * @return string
 */
protected function asciiEncodeString(string $string): string
{
    $sourceEncoding = mb_detect_encoding($string);
    $destinationEncoding = 'CP437'; // Extended ASCII - Codepage 437
    $string = iconv($sourceEncoding, $destinationEncoding, $string);
    return $string;
}

UDP with PHP send and receive sample messages

With PHP you can send very simple packets over UDP on your own computer. To test this, do you need a transmitter and a receiver. Communicate both via the local IP on port in the Biepsiel 20010. The samples must be run on the console.

Transmitter:

<?php
$address = '127.0.0.1';
$port = 20010;
$beat_period = 1;

$fp = stream_socket_client("udp://$address:$port", $errno, $errstr);
if (!$fp) {
 die("ERROR: $errno - $errstr");
}

while (true) {
 $message = sprintf(
 '%s send: %s'. PHP_EOL,
 date('c'),
 rand(0, 1000000)
 );
 fwrite($fp, $message);
 echo $message;

 sleep($beat_period);
}

Receiver:

<?php

$address = '127.0.0.1';
$port = 20010;

$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socket, $address, $port);

if ($socket === false) {
 throw new \RuntimeException(
 sprintf(
 'could not connect to socket address %s on port %s. Error: %s %s',
 $address,
 $port,
 socket_last_error(),
 socket_strerror(socket_last_error())
 )
 );
}

while (true){
 echo socket_read ($socket, 1024);
}

Read more UDP frames with PHP parallel with socket_select()

You can perform operations very difficult parallel in PHP, read but for which there are multiple sockets socket_select() Function. This way, more can be socket connections parallel readout.

The example 2 UDP socket connections created and at the same time read:

function createSocket(string $ip, int $port)
{
    $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
    //set non blocking read
    socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
    socket_bind($socket, $ip, $port);

    if ($socket === false) {
        throw new \RuntimeException(
            sprintf(
                'could not connect to socket address %s on port %s. Error: %s %s',
                $ip,
                $port,
                socket_last_error(),
                socket_strerror(socket_last_error())
                )
        );
    }
    return $socket;
}
function readSockets()
{
 $waitTimeoutSeconds = 1;

 $socket1 = $this->createSocket('127.0.0.1', 20001);
 $socket2 = $this->createSocket('127.0.0.1', 20002);

 $sockets['socket1'] = $socket1;
 $sockets['socket2'] = $socket2;

 $read = $sockets;
 $write = null;
 $except = null;

 if (socket_select($read, $write , $except, $waitTimeoutSeconds))
 {
 // loop through the sockets that showed activity
 if (isset($read['socket1'])) {
    // socket 1 got a message
    $content1 = socket_read ($socket1, 1024);
 }
 if (isset($read['socket2'])) {
    // socket 2 got a message
    $content2 = socket_read ($socket2, 1024);
 }

 } else {
 throw new \RuntimeException('could not read any socket');
 }

 socket_close($socket1);
 socket_close($socket2);
}

PHP-XMLReader for very large files example

Around with PHP to parse large XML files, do you want to use a SAX parser, the XML reads files from top to bottom and not transforming into an object. This is the XMLReader PHP.

An example:

$data = new Data();
$reader = new \XMLReader();
$reader->open($file);

while ($reader->read()) {
    if ($reader->nodeType == \XMLReader::ELEMENT) {
        switch ($reader->name) {
            case "tagName1" :
                $node = new \SimpleXMLElement($reader->readOuterXML());
                $attributes = $node->attributes();
                $entity = new Entity();
                $entity->setId($attributes['id']);
                $entity->setName($attributes['name']);
                $entity->setCode($attributes['code']);
                $data->addEntity($entity);

                break;

            case  "tagName2":
                $node = new \SimpleXMLElement($reader->readOuterXML());
                $attributes = $node->attributes();
                $entity = new OtherEntity();
                $entity->setId($attributes['id']);
                $entity->setName($attributes['name']);
                $entity->setCode($attributes['code']);
                $data->addOtherEntity($entity);

                break;
        }
    }
}

Twig extension to sort of entities by DateTime property

If one wants to sort a collection of doctrine in the template after a time stamp (createdAt the example), before actually make this.

If this is not possible, e.g.. in the Sonata Admin Bundle, then you can use this twig extension:

{% foo| sortByCreatedAt('asc') %}

Twig extension code:

<?php

namespace App\Twig;

use App\Entity\Tag;
use Doctrine\ORM\PersistentCollection;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class AppExtension extends AbstractExtension
{
    public function getFilters()
    {
        return array(
            new TwigFilter('sortByCreatedAt', array($this, 'sortByCreatedAt')),
        );
    }

    /**
     * @param PersistentCollection $objects
     * @return mixed
     */
    public function sortByCreatedAt($objects, $direction = 'asc')
    {
        $objects = $objects->toArray();
        usort($objects, function ($a, $b) use($direction) {
            if ($direction === 'asc') {
                return $a->getCreatedAt() >  $b->getCreatedAt();
            } elseif ($direction === 'desc') {
                return $a->getCreatedAt() <  $b->getCreatedAt();
            } else {
                throw new \Exception('unknown sort direction');
            }

        });
        return $objects;
    }
}

Strato und MySQL: General error: 1709 Index column size too large. The maximum column size is 767 bytes.

A customer following error message was shown to me, When I tried the database have symfony to create:

General error: 1709 Index column size too large. The maximum column size is 767 bytes.

This is because, the Strato strange setting in their managed hosting packages such as z.B. has the STRATO PowerWeb. Strato unfortunately won't change this setting, but you can in symfony in the doctrine.yaml (config.YAML) change the charset, Symfony works well on a Strato Server:

doctrine:
    dbal:
        # configure these for your database server
        driver: 'pdo_mysql'
        server_version: '5.6'
        charset: utf8
        default_table_options:
            charset: utf8
            collate: utf8_general_ci

Symfony security passwords hash with the PasswordEncoder

The PasswordEncoder the symfony framework secure hashes of passwords in the database is very well suitable also in future to save and configure Central.

The SecurityBundle must if necessary. to be installed:

composer require symfony/security-bundle

Putting this in the security.yaml, you want to use what hashing algorithm for which entity:

security:
    encoders:
        App\Entity\User: bcrypt

The entity must implement the UserInterface: more…