Nomad PHPMySQL: Analysis, Understanding, andOptimization of Queries (17.2.2017, 05:01 UTC)

May 2017 - US
Presented By

Michael Moussa
May 18, 2017
20:00 CDT

The post MySQL: Analysis, Understanding, and
Optimization of Queries
appeared first on Nomad PHP.

Link
Nomad PHPCode Coverage for Total Securityin Application Migrations! (17.2.2017, 05:01 UTC)

May 2017 - EU
Presented By

Dana Luther
May 18, 2017
20:00 CEST

The post Code Coverage for Total Security
in Application Migrations!
appeared first on Nomad PHP.

Link
PHP: Hypertext PreprocessorPHP 7.1.2 Released (17.2.2017, 00:00 UTC)
The PHP development team announces the immediate availability of PHP 7.1.2. Several bugs have been fixed. All PHP 7.1 users are encouraged to upgrade to this version. For source downloads of PHP 7.1.2 please visit our downloads page, Windows source and binaries can be found on windows.php.net/download/. The list of changes is recorded in the ChangeLog.
Link
SitePoint PHPWriting Async Libraries – Let’s Convert HTML to PDF (16.2.2017, 17:00 UTC)

I can barely remember a conference where the topic of asynchronous PHP wasn't discussed. I am pleased that it's so frequently spoken about these days. There's a secret these speakers aren't telling, though...

Making asynchronous servers, resolving domain names, interacting with file systems: these are the easy things. Making your own asynchronous libraries is hard. And it's where you spend most of your time!

Vector image of parallel racing arrows, indicating multi-process execution

The reason those easy things are easy is because they were the proof of concept – to make async PHP competitive with NodeJS. You can see this in how similar their early interfaces were:

var http = require("http");
var server = http.createServer();

server.on("request", function(request, response) {
    response.writeHead(200, {
        "Content-Type": "text/plain"
    });

    response.end("Hello World");
});

server.listen(3000, "127.0.0.1");

This code was tested with Node 7.3.0

require "vendor/autoload.php";

$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$server = new React\Http\Server($socket);

$server->on("request", function($request, $response) {
    $response->writeHead(200, [
        "Content-Type" => "text/plain"
    ]);

    $response->end("Hello world");
});

$socket->listen(3000, "127.0.0.1");
$loop->run();

This code was tested with PHP 7.1 and react/http:0.4.2

Today, we're going to look at a few ways to make your application code work well in an asynchronous architecture. Fret not – your code can still work in a synchronous architecture, so you don't have to give anything up to learn this new skill. Apart from a bit of time...

You can find the code for this tutorial on Github. I've tested it with PHP 7.1 and the most recent versions of ReactPHP and Amp.

Promising Theory

There are a few abstractions common to asynchronous code. We've already seen one of them: callbacks. Callbacks, by their very name, describe how they treat slow or blocking operations. Synchronous code is fraught with waiting. Ask for something, wait for that thing to happen.

So, instead, asynchronous frameworks and libraries can employ callbacks. Ask for something, and when it happens: the framework or library will call your code back.

In the case of HTTP servers, we don't preemptively handle all requests. We don't wait around for requests to happen, either. We simply describe the code that should be called, should a request happen. The event loop takes care of the rest.

A second common abstraction is promises. Where callbacks are hooks waiting for future events, promises are references to future values. They look something like this:

readFile()
    ->then(function(string $content) {
        print "content: " . $content;
    })
    ->catch(function(Exception $e) {
        print "error: " . $e->getMessage();
    });

It's a bit more code than callbacks alone, but it's an interesting approach. We wait for something to happen, and then do another thing. If something goes wrong, we catch the error and respond sensibly. This may look simple, but it's not spoken about nearly enough.

We're still using callbacks, but we've wrapped them in an abstraction which helps us in other ways. One such benefit is that they allow multiple resolution callbacks...

$promise = readFile();
$promise->then(...)->catch(...);

// ...let's add logging to existing code

$promise->then(function(string $content) use ($logger) {
    $logger->info("file was read");
});

There's something else I'd like us to focus on. It's that promises provide a common language – a common abstraction – for thinking about how synchronous code can become asynchronous code.

Let's take some application code and make it asynchronous, using promises...

Continue reading %Writing Async Libraries – Let’s Convert HTML to PDF%

Link
PHP ClassesMaking PHP 7.2 More Secure with LibSodium Extension - 5 Minutes Lately in PHP podcast episode 80 (16.2.2017, 11:38 UTC)
By Manuel Lemos
Many PHP developers still use the mcrypt extension for encrypting and decrypting data. However, that extension is based on a C library that is not being maintained anymore by its developers. PHP applications are at risk of being exposed to eventual vulnerabilities that may be discovered in mcrypt but its developers will not fix them.

A better alternative is to use the LibSodium extension proposed by the security expert Scott Arciszewski to become part of the core PHP distribution since PHP 7.2.

This was one of the main topics discussed by Manuel Lemos and Christian Vigh (the PHP Innovation Award Winner of the Year of 2016) on the episode 80 of the Lately in PHP podcast.

In this episode they also talked about other proposals for future PHP versions like improving the mail() function with options passed using the 5th parameter, final modifier for class constants, type hinting for static objects, using namespaces for global functions, type hinting for arrays with values of the same type .

This article also contains a podcast summary as a text transcript and a 5 minute video of the summary.

Listen to the podcast, or watch the hangout video, or read the transcript text to learn more about these interesting PHP topics.
Link
Rob AllenStand-alone usage of Zend-InputFilter (15.2.2017, 12:28 UTC)

Any data that you receive needs to be checked and validated. There are number of ways to do this including PHP's filter_var, but I prefer Zend-InputFilter. This is how to use it as a stand-alone component.

Installation

Firstly, we install it using Composer:

$ composer require zendframework/zend-inputfilter
$ composer require zendframework/zend-servicemanager

You don't have to have ServiceManager, but it makes working with InputFilter much easier, so it's worth installing.

Create the InputFilter

The easiest way to create an InputFilter is to use the provided Factory class. Let's consider an Author entity that has the properties: author_id, name, biography & date_of_birth. We can create an input filter like this:

use Zend\InputFilter\Factory as InputFilterFactory;

class Author
{
    protected $author_id;
    protected $name;
    protected $biography;
    protected $date_of_birth;

    // ...

    protected function createInputFilter()
    {
        $factory = new InputFilterFactory();
        $inputFilter = $factory->createInputFilter([
            'author_id' => [
                'required' => true,
                'validators' => [
                    ['name' => 'Uuid'],
                ],
            ],
            'name' => [
                'required' => true,
                'filters' => [
                    ['name' => 'StringTrim'],
                    ['name' => 'StripTags'],
                ],
            ],
            'biography' => [
                'required' => false,
                'filters' => [
                    ['name' => 'StringTrim'],
                    ['name' => 'StripTags'],
                ],
            ],
            'date_of_birth' => [
                'required' => false,
                'validators' => [
                    ['name' => 'Date'],
                    [
                        'name' => 'LessThan',
                        'options' => [
                            'max' => date('Y-m-d'),
                            'inclusive' => true,
                        ],
                    ],
                ],
            ],
        ]);

        return $inputFilter;
    }
}

The createInputFilter() method takes an associative array where the key is the name of the input and then the value is a specification. There are a number of elements in the specification, but we usually just specify required, filters and validators.

required This can be either true or false. If false, then the validators do not execute, but the filters do.
filters An optional array of Zend-Filters. A filter modifies the supplied data before it is passed to the validators (if any). The filtered data is used by the rest of the application. In this example, we have added two filters: StringTrim & StripTags.
validators An optional array of Zend-Validators. A validator will test the filtered value for the input and fail if the data is not valid. If any validator fails, then the entire InputFilter is invalid.

This particular input filter requires that author_id and name are present, but that biography and date_of_birth are optional. The author_id must be a UUID, the name & biography must not have leading or trailing whitespace or no HTML tags and the date_of_birth, if present, must be a valid date in the past.

Using the InputFilter

To use the InputFilter, we set the data and then call isValid(). This can be done in a validate() method that looks like this:

Use Crell\ApiProblem\ApiProblem;
use Error\Exception\ProblemException;

Class Author
{
    // ...

    /**
     * Create an author
     *
     * @param  array $data
     * @return Author
     * @throws ProblemException
     */
    public static function createAuthor($data)
    {
        $inputFilter = $this->createInputFilter();
        $inputFilter->setData($data);

        if ($inputFilter->isValid()) {
            return new Author($inputFilter->getValues());
        }

        $problem = new ApiProblem('Validation failed');
        $problem->setStatus(400);
        $problem['errors'] = $inputFilter->getMessages();

        throw new ProblemException($problem);
    }
}

In this case, it's an API, so the data has come from a PUT or POST

Truncated by Planet PHP, read more at the original (another 1414 bytes)

Link
PHP ClassesTutorial on How to Control an Android Phone or Tablet using PHP with Termux App (15.2.2017, 12:05 UTC)
By Luis Martinez Ulloa
The Termux application allows running many well known Linux applications on an Android phone, tablet or any other kind of device.

This allows running PHP either from the Termux shell as a console script or as a Web server.

Read this article to learn how to execute PHP scripts from inside a Android device and expose to PHP some Android functionalities using the Termux application.
Link
thePHP.ccThe Death Star Version Constraint (15.2.2017, 07:00 UTC)
Link
Adam CulpSetting up local step debugging with PhpStorm (14.2.2017, 14:31 UTC)

Setting up PHP debugging in an IDE with a local development environment has gotten so easy it can be done in a few automated steps. In this post I will demonstrate how to get step debugging functioning with PhpStorm and Zend Debugger when the server is set up on a local environment.

To begin with, I had the following:

  • Local installation of Zend Server 8.5.+ (basic LAMP stack, but with Zend Debugger included in the Zend Server installation). Alternatively I could have had a vanilla LAMP environment with Xdebug.
  • Ensure that Z-Ray is active in the Zend Server settings.
  • A local project set up on PhpStorm, without the server set up in the PhpStorm project configuration. (in this example I have a Zend Expressive Skeleton ready)
  • The local project set up as an Apache virtualhost.

With the project open in PhpStorm I click the icon to inform the IDE to start listening for debugging sessions. (Usually in the upper right corner, looks like a telephone receiver with a red indicator that it is not listening, and turns green when you click it)

Then a browser with the application rendered I click the debug icon in the Z-Ray toolbar at the foot of the window, and select the desired debugging action.

This will cause PhpStorm to prompt after it receives the debug connection from Zend Debugger. In most cases we can simply click Accept and let things happen normally.

That’s about it, we are debugging!

Behind the scenes, PhpStorm created a site and associated it with the project.

Of course we could have created the server ahead of time and not be prompted to Accept the incoming connection, but what is the fun in that?

Truncated by Planet PHP, read more at the original (another 716 bytes)

Link
SitePoint PHPAchieving Modular Architecture with Forwarding Decorators (13.2.2017, 17:00 UTC)

As your web application becomes larger, you certainly start to think more about designing a flexible, modular architecture which is meant to allow for a high amount of extensibility. There are lots of ways to implement such architecture, and all of them circle around the fundamental principles: separation of concerns, self-sufficiency, composability of the parts of an app.

There is one approach which is rarely seen in PHP software but can be effectively implemented -- it involves using native inheritance to provide manageable patching of the software code; we call it the Forwarding Decorator.

Picture for attention

Introduction To The Concept

In this article, we are going to observe the implementation of the Forwarding Decorator approach and its pros/cons. You can see the working demo application at this GitHub repository. Also, we'll compare this approach to other well-known ones such as hooks, and code patching.

The main idea is to treat each class as a service and modify that service by extending it and reversing the inheritance chain through code compilation. If we build the system around that idea, any module will be able to contain special classes (they will be marked somehow to separate from the usual classes), which can inherit from any other class and will be used anywhere instead of the original object.

Comparison of the original and compiled classes

That's why it is called Forwarding decorators: they wrap around the original implementation and forward the modified variant to the forefront to be used instead.

The advantages of such an approach are obvious:

  • modules can extend almost any part of the system, any class, any method; you don't have to plan extension points in advance.
  • multiple modules can modify a single subsystem simultaneously.
  • subsystems are loosely coupled and can be upgraded separately.
  • extension system is based on the familiar inheritance approach.
  • you can control extensibility by making private methods and final classes.

With great power comes great responsibility, so the drawbacks are:

  • you would have to implement some sort of compiler system (more about that later)
  • module developers have to comply with the public interface of the subsystems and not violate the Liskov substitution principle; otherwise other modules will break the system.
  • you will have to be extremely cautious when modifying the public interface of the subsystems. The existing modules will certainly break and have to be adapted to the changes.
  • extra compiler complicates the debugging process: you can no longer run XDebug on the original code, any code change should be followed by running the compiler (although that can be mitigated, even the XDebug problem)

How Can This System Be Used?

The example would be like this:

class Foo {
    public function bar() {
        echo 'baz';
    }
}

namespace Module1;

/**
 * This is the modifier class and it is marked by DecoratorInterface
 */
class ModifiedFoo extends \Foo implements \DecoratorInterface {
    public function bar() {
        parent::bar();
        echo ' modified';
    }
}

// ... somewhere in the app code

$object = new Foo();
$object->bar(); // will echo 'baz modified'

How can that be possible?

Achieving this would involve some magic. We have to preprocess this code and compile some intermediate classes with the reversed inheritance graph, so the original class would extend the module decorator like this:

Continue reading %Achieving Modular Architecture with Forwarding Decorators%

Link
LinksRSS 0.92   RDF 1.
Atom Feed   100% Popoon
PHP5 powered   PEAR
ButtonsPlanet PHP   Planet PHP
Planet PHP