SitePoint PHPSylius and Cutting Your Teeth on TDD (24.2.2017, 17:00 UTC)

Sylius logo

Sylius is an e-commerce application / framework based on Symfony. It boasts 100% code coverage, which is impressive for a PHP application of that size. In this article, we are going to walk through the different kinds of tests available and try out some Test and Behavior Driven Development (TDD/BDD). See the Sylius installation guide page for instructions, as this article assumes you have a working installation with example data and you can run Behat, PHPUnit and phpspec tests.

In the web root, there's a src folder which holds all Sylius-related code. This allows you to make use of the app folder for your application development without unnecessarily treading on Sylius' toes. As we are interested in test-driven development (first, write tests that fail before writing the code) let's dive in, the Sylius way.

We start by setting up our test database.

php bin/console doctrine:database:create --env=test
php bin/console doctrine:schema:create --env=test

Types of Sylius Tests

Some of the basics of the tools below have already been covered in this post, but we'll recap them here on Sylius examples to keep with the theme.

PHPUnit

Sylius comes with a lot of PHPUnit functional tests. The configuration file, phpunit.xml.dist, is in the web root and the unit tests are in the tests folder. From the root of our application, let's run tests in tests/Controller/CountryApiTest.php:

./vendor/phpunit/phpunit/phpunit -c ./phpunit.xml.dist tests/Controller/CountryApiTest

PHPUnit in action

The command is made up of 3 parts - path to PHPUnit, our configuration file and the unit test class. Open tests/Controller/CountryApiTest.php and take a look at the class. It extends JsonApiTestCase which we can trace back to ApiTestCase and WebTestCase, part of the Symfony framework package.

Phpspec

Behavior Driven Development (BDD) emerged from Test Driven Development (TDD), focusing attention on how a user interacts with an application and how the application behaves. SpecBDD is the part of BDD which considers how the smaller bits of an application work together to make things happen.

Sylius is installed with phpspec which is the tool required for this. In your root directory, there's also the phpspec.yml.dist configuration file. Specifications are written in PHP classes and may be grouped in suites.

Remember, Sylius is a big application so there are a lot of files. Open src/Sylius/Component/Order/spec/Model/OrderItemSpec.php.

The first thing to note is that no matter how deep the folder structure, you have specifications inside a spec folder and the source code the tests apply to is easy to find. If you look at the level of the spec folder, you'll see Model and inside it is an OrderItem class. The spec for that class is spec/Model/OrderItemSpec.php. Compare the functions and you can see how they are related.

When you run phpspec, you get more output with the --verbose option and with -fpretty you can get prettier outputs.

./bin/phpspec run -fpretty --verbose src/Sylius/Component/Order/spec/Model/OrderItemSpec.php

PHPSpec in action in Sylius

Continue reading %Sylius and Cutting Your Teeth on TDD%

Link
SitePoint PHPLaravel Dusk – Intuitive and Easy Browser Testing for All! (23.2.2017, 17:00 UTC)

End to end testing for JavaScript applications, particularly single-page-apps, has always been a challenge. To that end, Laravel released its 5.4 version recently with a new testing library: Dusk.

Laravel Dusk Logo

With the release of Dusk, Laravel hopes to give its users a common API for browser testing. It ships with the default ChromeDriver, and if we need support for other browsers, we can use Selenium. It will still have this common testing API to cater to our needs.

The tutorial will assume you're starting a new Laravel 5.4 app.

Installation

composer require laravel/dusk

This will install the most recent stable version of the package via Composer.

Next, we need to register DuskServiceProvider within our application. We can do it in a couple of ways:

Approach 1

We can include it in the providers array of our config/app.php file.

...

App\Providers\RouteServiceProvider::class,
Laravel\Dusk\DuskServiceProvider::class,
...

The problem with this approach is that DuskServiceProvider will be registered in our application for all the environments. We don't need Dusk to be available and registered in our production environment. We can avoid this with the second approach.

Approach 2

Register DuskServiceProvider in the AppServiceProvider class for specific environments:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Laravel\Dusk\DuskServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if ($this->app->environment('local', 'testing', 'staging')) {
           $this->app->register(DuskServiceProvider::class);
        }
    }
}

Next, to complete the installation process:

php artisan dusk:install

Dusk will provide a basic scaffolding of classes and directories. If we open the tests directory, we can see a new Browser directory with the necessary scaffolding for Dusk tests.

Our First Test

First, we will scaffold an authentication workflow using Laravel's pre-built authentication mechanism.

php artisan make:auth

Let us now create our first Dusk test:

php artisan dusk:make LoginTest

The above command will create a LoginTest class in our Browser directory.

class LoginTest extends DuskTestCase
{
    /**
     * A Dusk test example.
     *
     * @return void
     */
    public function test_I_can_login_successfully()
    {
        $this->browse(function ($browser) {
            $browser->visit('/login')
                    ->type('email', 'viraj@virajkhatavkar.com')
                    ->type('password', 'secret')
                    ->press('Login')
                    ->assertSee('You are logged in!');
        });
    }
}

In the above test case, we check whether a user can successfully log into the system and see a home page with a welcome message.

Note: To make this test succeed, we need to have an actual user in the database. For this demonstration, we have already configured a user in the database with the above credentials.

Continue reading %Laravel Dusk – Intuitive and Easy Browser Testing for All!%

Link
Remi ColletAdditional PHP packages for RHSCL (23.2.2017, 12:38 UTC)

Current situation about official repositories providing PHP Software Collections for  RHEL and CentOS users.

Since RHSCL 2.3 was released, RHEL users can install PHP 5.6 or PHP 7.0 without base système alteration, using the appropriate channel.

These packages are also available for CentOS users in the SCL repositories, managed by the SCLo SIG:

# yum --enablerepo=extras install centos-release-scl

So the CentOS project provides the infrastructure and hosting for 4 repositories:

  • centos-sclo-rh : same content than upstream RHSCL
  • centos-sclo-sclo : additional collections maintained by the community
  • centos-sclo-rh-testing : packages to be tested (RHSCL beta version)
  • centos-scl-sclo-testing : package to be tested, maintained by the community

RHSCL users wishing to use these additional packages can configure the centos-sclo-sclo repository by using the  centos-release-scl Copr repository:

# cd /etc/yum.repos.d/
# wget https://copr.fedorainfracloud.org/coprs/rhscl/centos-release-scl/repo/epel-7/rhscl-centos-release-scl-epel-7.repo
# yum install centos-release-scl

If you are interested by these packages, I recommend to follow the sclorg@redhat.com mailing list where possible issues are discussed, and changes announced. Thanks for using this list for your feedback (testing packages) or any other request. New contributor are also welcome.

Information and documentation on https://www.softwarecollections.org/.

Development is tracked on sclorg-distgit.

Here is the list of available additional packages in centos-sclo-sclo on Feb 23th 2017:

# Package name Version Distribution Comments
  sclo-php56-php-pecl-apcu
sclo-php70-php-pecl-apcu
4.0.10
5.18
6, 7  
  sclo-php70-php-pecl-apcu-bc 1.0.3 6, 7  
  sclo-php56-php-pecl-apfd
sclo-php70-php-pecl-apfd
1.0.1 6, 7  
  sclo-php56-php-pecl-geoip
sclo-php70-php-pecl-geoip
1.1.1 7  
  sclo-php56-php-pecl-http
sclo-php70-php-pecl-http
2.5.6
3.0.1
6, 7  
  sclo-php56-php-pecl-igbinary
sclo-php70-php-pecl-igbinary
2.0.1 6, 7  
  sclo-php56-php-pecl-imagick
sclo-php70-php-pecl-imagick
3.4.3 6, 7  
  sclo-php56-php-pecl-lzf
sclo-php70-php-pecl-lzf
1.6.5 6, 7  
  sclo-php70-php-pecl-memcached 3.0.3 7 testing
  sclo-php56-php-pecl-mongodb
sclo-php70-php-pecl-mongodb
1.1.10 6, 7  
  sclo-php70-php-pecl-msgpack 2.0.2 6, 7 testing
  sclo-php56-php-pecl-propro
sclo-php70-php-pecl-propro
1.0.2
2.0.1
6, 7  
  sclo-php56-php-pecl-raphf
sclo-php70-php-pecl-raphf
1.1.2

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

Link
PHP ClassesPHP Articles Report February 2017 Edition (23.2.2017, 09:08 UTC)
By Manuel Lemos
This is the February 2017 edition of the podcast hangout recorded by Manuel Lemos and Arturs Sosins to comment on the latest outstanding PHP articles published recently.

In this edition they discuss articles about the fastest method to evaluate the performance of a PHP Web application hire a server that can handle its needs in terms of CPU, RAM and disk, sending postal mail and cheques using an API, gamify a site the site link secret path, parsing and converting text with an amount in English to the respective number, and a simple tutorial on how to use MySQL with PDO in PHP 7.

Listen to the podcast, or watch the hangout video to learn more about these PHP articles.
Link
PHP ClassesThe Best WordPress Security Plugins and Support Services of 2017 and 2016 Comparison of Free and Commercial Versions (22.2.2017, 12:34 UTC)
By Haseeb Ahmad Basil
WordPress is the most popular Web publishing platform. Since it is used by many Web site owners, it is also a target of many security exploits.

Many WordPress site owners do not know enough about security to protect their sites from being abused. Therefore they need to use plugins and tools to help them prevent and eventually fix security issues.

Read this this article to compare the features of the most recommended WordPress security plugins so you can pick one that addresses your needs.
Link
Piotr Pasich7 PHP UK 2017’s talks you must see (22.2.2017, 06:38 UTC)
phpukPhpUK is a conference I have wanted to attend for a long long time. I had watched all the videos on youtube really carefully for the last few years and always got this weird feeling this might be one of the best and most important conferences in Europe. So, here I am. 3 totally different […]
Link
SitePoint PHPSourcehunt: Idea of the Month and 6 Interesting Repos! (21.2.2017, 16:57 UTC)

It's time for our monthly hunt for new open source libraries to use and contribute to!

If you're new to Sourcehunt, it's our monthly post for promoting open source projects that seem interesting or promising and could use help in terms of Github stars or pull requests.

It's our way of giving back - promoting projects that we use (or could use) so that they gain enough exposure to attract a wider audience, a powerful community and, possibly, new contributors or sponsors.

Sourcehunt logo


genkgo/archive-stream [5 ★]

We stumbled upon this package following this very interesting read about streamed file zipping and downloading in PHP.

This package provides a memory efficient API for streaming ZIP files as PSR 7 messages. It comes with certain limitations, namely that only the Zip64 (version 4.5 of the Zip specification) format is supported, and files cannot be resumed if a download fails before finishing, but apart from that, using it is incredibly straightforward if you're already wading through the PSR-7 waters:

$archive = (new Archive())
    ->withContent(new CallbackStringContent('callback.txt', function () {
        return 'data';
    }))
    ->withContent(new StringContent('string.txt', 'data'))
    ->withContent(new FileContent('file.txt', 'local/file/name.txt'))
    ->withContent(new EmptyDirectory('directory'));

$response = $response->withBody(
    new Psr7Stream(new ZipReader($archive))
);

The library, while having many contributors who have done a professional job of fool-proofing it, and being over 8 months old, lacks exposure. Oddly enough, there are no issues (the issues feature itself is disabled) and no PRs to review, but the authors could always use more testers, tech writers to present the lib in blogs, and maintainers.

How do you usually send ZIPs, if at all? Why not give this a go?

Continue reading %Sourcehunt: Idea of the Month and 6 Interesting Repos!%

Link
Adam CulpSetting up local step debugging with Zend Studio (21.2.2017, 14:30 UTC)

Setting up debugging in an IDE with a local PHP development environment has gotten so easy it can be done in a couple automated steps. In this post I will demonstrate how to get step debugging functioning with Zend Studio 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 Zend Studio, without the server set up in the Zend Studio project configuration. (in this example I have a Zend Expressive Skeleton ready)
  • The local project set up as an Apache virtualhost.

Ensure Zend Studio is running with the project we will debug open.

In 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 Zend Studio to prompt if we desire to use the Debug Perspective after it receives the debug connection from Zend Debugger. In most cases we can simply click Yes and let things happen normally.

That’s about it, we are debugging!

Closing

This was a very simplistic local development environment setup. We didn’t have a firewall to contend with, and the server was set up locally rather than inside a virtual machine. I have other posts, linked below, to help with some of these alternative setups.

Happy Debugging!

Other posts on Debugging you may find helpful:

Link
Paul M. JonesWikiMedia, Clean Architecture, and ADR (21.2.2017, 13:30 UTC)

tl;dr: Action-Domain-Responder is a natural fit for the HTTP user-interface portions of Clean Architecture (or Hexagonal), especially with Domain Driven Design. Just be sure to remember to separate the HTTP response presentation from the action code.


I.

Jeroen de Dauw has a fantastic post on Implementing the Clean Architecture in PHP, with Domain Driven Design elements. You should read the whole thing, and examine the implementation codebase, for a number of useful insights. Though I might quibble over some elements of the implementation, I think it is a good offering, and serves as a solid reference point.

In his article, Jeroen notes they are using Silex for their HTTP user-interface system, and describes the logic of each route action:

Inside this [Silex action] we construct our framework agnostic request model and invoke the Use case with it. Then we hand over the response model to a presenter to create the appropriate HTML or other such format.

That is a very near paraphrase of Action-Domain-Responder:

  • The Action marshals input from the HTTP request
  • The Action invokes a Domain element with that input and gets back a result
  • The Action passes that result to a Responder to build the HTTP response

In Jeroen’s implementation, each Action is a closure defined in the routes.php file. The Action marshals input from the HTTP request using a “request model” (an input object tailored to the domain) and passes it to a “use case.” Each “use case” is an entry point into the Domain, and returns a “response model” (the domain result).

The only place where Jeroen’s implementation deviates from ADR is that the Action code builds the presentation itself, instead of handing off to a Responder. (This may be a result of adhering to the idioms and expectations specific to Silex.)

Because the rest of the implementation is so well done, refactoring to a separated presentation in the form of a Responder is a straightforward exercise. Let’s see what that might look like.

II.

First, as an example, review the code in the check-iban action. The following reorganization of that action code makes the ADR pattern more obvious:

<?php
$app->get(
    'check-iban',
    function( Request $request ) use ( $app, $ffFactory ) {

        // marshal input
        $input = new Iban( $request->query->get( 'iban', '' ) );

        // invoke domain and get back result
        $result = $ffFactory->newCheckIbanUseCase()->checkIban($input);

        // presentation
        return $app->json(
            $ffFactory->newIbanPresenter()->present( $result )
        );
    }
);
?>

Very clear and straightforward. However, the presentation work is embedded in the action with the $app->json(...) call. (My guess is that’s probably a result of working with existing Silex idioms.)

Another good example is the list-comments.html action. Reorganizing the logic to make the ADR pattern more obvious gives us the following:

<?php
$app->get(
    'list-comments.html',
    function( Request $request ) use ( $app, $ffFactory ) {

        // marshal input
        $input = new CommentListingRequest(
            10,
            (int)$request->query->get( 'page', '1' )
        );

        // invoke domain and get back result
        $result = $ffFactory
            ->newListCommentsUseCase()
            ->listComments( $input );

        // presentation
        return new Response(
            $ffFactory->newCommentListHtmlPresenter()->present(
                $result,
                (int)$request->query->get( 'page', '1' )
            )
        );
    }
);
?>

Again, the presentation work is embedded in the action code.

In general, it is better to completely separate the presentation work from the action code. Remember that in an HTTP context, the presentation is not just the body of the HTTP response.

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

Link
Voices of the ElePHPantInterview with Chris Hartjes (21.2.2017, 10:00 UTC) Link
LinksRSS 0.92   RDF 1.
Atom Feed   100% Popoon
PHP5 powered   PEAR
ButtonsPlanet PHP   Planet PHP
Planet PHP