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.

Console of commands

Console of commands and normal controller differ in Symfony complete in terms of syntax, However, both offer same functionality.

Here has Yii the advantage of, to behave in a very similar, and to use the same syntax for controller.

Database interaction

Yii 2 relies on an own database wrapper, with the database operations and migrations are made. Databases need to about Migrations be created and it can then the entities are generated objects. Yii relies on the ActiveRecord pattern, What is unfortunately not ideal from a performance perspective in the sleep to the repository pattern of symfony, Since each entities object dragging unnecessary functionality around with you. On the other hand, everything is centrally stored in a file, be it labels or error messages for forms, Validators for individual attributes or queries on the table. The way each entity is comfortable to use a different database connection. The data can be displayed very simply using the GridView.

Symfony uses doctrine as ORM Mapper and thus has the advantage, that tables are automatically generated based on the entities definitions, and you can use a much larger range of functions, as well as more auto completition in the IDE will receive as a result of the object-oriented style of doctrine. There is no direct component to display the data in a ListView, Here you can create administration surfaces on the Sonata project back attack, can be used to create first-class backends.

Code generators

Yii has a very good code generator called GII, the in addition to the standard features such as model and extensions skeletons also CRUD interfaces and forms very nicely and quickly can be generated on the console and also with a Web frontend.

Symfony has recently Symfony maker bundle, which can be very well adapted, but not enough on the functionality of GII used.

Views

Yii has no templating engine home, everything is permitted and is done in the view, It's full of PHP, actually an anti pattern.

Symfony has its own, very nice templating engine: Twig, with the very nice view and application logic/code can be separated.

REST

Yii take an ausgewöhlich simple and extensive REST Implemnetierung with it, one very simple with the REST creating interfaces can including HATEOAS.

Symfony has its own FOSRest Extension, that is but not as elegant as that of Yii. HATEOAS is not available.

Testing

Yii has a lot of static method calls, for now difficult to test.

Symfony uses dependency injection for all services and can be perfectly tested.

Conclusion:

Symfony is a professional basis for large projects to be tested. Yii is very well suited for quickly to build prototypes and smaller projects.

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;
        }
    }
}

Microsoft IIS REST API allow by PUT, DELETE

To the IIS 7.5 all HTTP verbs like PUT, POST, DELETE and PATCH to enable, need to disable the following modules and handlers in the web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
      <modules>
         <remove name="WebDAVModule" />
      </modules>
        <handlers>
            <remove name="WebDAV" />
            <remove name="OPTIONSVerbHandler" />
            <remove name="TRACEVerbHandler" />
        </handlers>
    </system.webServer>
</configuration>

Microsoft IIS SSL certificate create for localhost for chrome 60 with SAN

To create a certificate for IIS under IIS, should you create a SSL certificate with openssl (comes with GIT in C:\Program FilesGitusrbin).

With the two commands, you can create a .pfx file, also see chrome 60 He runs on option chrome://flags/#allow-insecure-localhost.

openssl req  -newkey rsa:2048 -x509   -nodes -keyout server.key  -new  -out server.crt  -subj /CN=localhost  -reqexts SAN -extensions SAN  -config openssl.cnf -sha256 -days 36500
openssl pkcs12 -export -out server.pfx -inkey server.key -in server.crt

You need a configuration file OpenSSL.cnf: more…