Bruno ŠkvorcInterview: Tom Oram and Rob Allen (17.4.2014, 16:00 UTC)

In our second interview, we talk to Tom Oram, who works for a small development firm in Wales and Rob Allen, from Nineteen Feet.

These two developers have a solid wealth of PHP experience and knowledge and have helped me refine my ideas and approaches on many occasions. With that, we’ll start with Tom.

Tom Oram

What lead you to PHP?

A job. I was offered a job using a language I knew nothing about called PHP. It was PHP version 3 at the time, so much less advanced than it is now. Since then, I’ve been using PHP almost every day of my working life.

What have been the things about PHP that bit you?

In previous versions I’ve had various things which have caused confusion and frustration, most notably references and object copying in PHP 4.

However in PHP 5 I don’t really have anything that really catches me out. There are, however, things which I think could be improved or added to make the language easier and more consistent to use.

What have been the highlights or redeeming features

I guess the best thing about PHP is the speed in which you can get going. You can have an idea and very quickly try it out while at the same time it’s very well suited to larger and more complex projects as well.

What are the compelling PHP features for you?

For me I love interfaces and the fact that static typing is becoming more and more possible while still allowing dynamic typing.

What do you want to see added to the language?

  • Type hinting for scalar parameter types
  • Type hinting of return values
  • Nested classes

Why PHP over Ruby, Python, Go, etc?

Honestly I think they all have their own pros and cons. In many ways I think the other languages are designed better and are more consistent.

However if you’re used to programming in a statically typed language (especially Java) then PHP might seem easier to relate to than Python or Ruby.

Do you see yourself moving to another language in the future?

I use other languages all the time, and if a job is better suited to another language I will use that. However for web-based projects I always reach for PHP first, I currently have no intention of changing that.

Do you have a custom framework/setup?

Continue reading %Interview: Tom Oram and Rob Allen%

Link
Paul M. JonesFirst Aura v2 Beta Releases of Web_Project, Cli_Project, and Framework_Project (17.4.2014, 15:27 UTC)

Earlier this week, we put the final touches on the “micro/macro” frameworks for v2 web projects and v2 command line projects. Although these had been delayed a bit while working out the Aura.Di v2 beta release, they both now have their first “Google beta” releases!

… The idea is that [Aura.Web_Project] starts as a very minimal system, with only router, dispatcher, request, and response functionality. But thanks to the Composer-assisted configuration system, it’s very easy to add whatever functionality you want, making the project as large or as small as you need. …

Aura.Cli_Project takes exactly the same approach, but for command-line applications. It consists of a “context” and standard I/O system (the equivalents of a request and response), along with a console and dispatcher. It uses the same configuration system as Web_Project, so you start with a very minimal system that grows only as you need it.

Each project is little more than a skeleton around a core “kernel” package. The Aura.Web_Kernel is what actually provides the glue to connect the underlying library packages together, as does the Aura.Cli_Kernel.

Keeping the kernel separate from the project means we can update the kernel without having to re-install a project.

via First v2 Beta Releases of Web_Project, Cli_Project, and Framework_Project.

Link
Bruno ŠkvorcGetting Started with PHP Underscore (16.4.2014, 17:00 UTC)

If you’ve ever used the Backbone framework for JavaScript, you’ll already be familiar with Underscore. Indeed, it’s become incredibly useful for JavaScript developers in general. But did you know that it’s been ported to PHP?

In this article I’ll take a look at Underscore, what it can do, and provide some examples of where it might be useful.

What is Underscore?

Underscore describes itself as a “utility belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects. It’s the tie to go along with jQuery’s tux, and Backbone.js’s suspenders.”

Most notably, Underscore provides a bunch of utilities for working with collections and arrays, some for working with objects, basic templating functionality and a number of other useful functions.

The functions which operate on collections and arrays can be particularly useful when dealing with JSON, which makes it great for handling responses from web services.

Continue reading %Getting Started with PHP Underscore%

Link
Federico CargneluttiTDD: Checking the return value of a Stub (15.4.2014, 23:32 UTC)

State verification is used to ensure that after a method is run, the returned value of the SUT is as expected. Of course, you may need to use Stubs on a test double or a real object to tell the object to return a value in response to a given message.

In Java, you declare a method’s return type in its method declaration, this means that the type of the return value must match the declared return type or otherwise you will get a compiler error. In PHP, for example, you dynamically type the return value within the body of the method. This means that PHP mocking libraries cannot check the type of the return value and provide guarantees about what is being verified.

This leads to the awkward situation where a refactoring may change the SUT behaviour and leave a stub broken but with passing tests. For example, consider the following:

Developer (A) creates 2 classes, Presenter and Collaborator:

class Presenter
{
    protected $collaborator;

    public function __construct(Collaborator $obj)
    {
        $this->collaborator = $obj;
    }

    public function doSomething()
    {
        $limit = 1;
        $stories = $this->collaborator->getStories($limit);
        // ...
        return $stories;
    }
}

class Collaborator
{
    public function getStories($limit)
    {
        return array();
    }
}

Then writes a test case:

class PresenterTest extends PHPUnit_Framework_TestCase
{
    // Behaviour verification
    public function testBehaviour()
    {
        $mock = $this->getMock('Collaborator', array('getStories'));
        $mock->expects($this->once())
            ->method('getStories')
            ->with(
                $this->logicalAnd(
                    $this->equalTo(1), $this->isType('integer')
                )
            );

        $presenter = new Presenter($mock);
        $presenter->doSomething();
    }

    // State verification
    public function testState()
    {
        $stub = $this->getMock('Collaborator', array('getStories'));
        $stub->expects($this->once())
            ->method('getStories')
            ->will($this->returnValue(array()));

        $presenter = new Presenter($stub);
        $data = $presenter->doSomething();

        $this->assertEquals(array(), $data);
    }
}

The Developer (A) uses a mock to verify the behaviour (a mockist practitioner) and a stub to verify the method worked correctly. The first test asserts that the expectation is met and the second one that the given condition is true. Finally, the Developer runs and watches all of the tests pass. Great!

The next day Developer (B) decides to makes some changes to the Collaborator class and return NULL if there are no stories:

class Collaborator
{
    public function getStories($limit)
    {
        $stories = array();
        if (count($stories) < 1) {
            return;
        }

        return $stories;
    }
}

The implementation of the method-under-test changed, it now returns a different data type, null instead of array. This means that our second test should fail, but it doesn’t. The test still asserts that the given condition is true, even though the return type is different. This is a problem. It means that our second test is unable to verify the correct state of the SUT (and its collaborator).

This is because most PHP mocking libraries are heavily influenced by Java (PHPUnit was originally a port of JUnit), and Java doesn’t have this problem. In PHP, the method’s return type is not a required elements of a method declaration, so developers can define it at run time and return whatever type they want.

The solution

You can use DocBlock annotations to make sure the data type of the returned value matches the one defined in the DocBlock. For this to work you need to set the return value using ReturnValue instead of PHPUnit_Framework_MockObject_Stub_Return. For example:

class PresenterTest extends PHPUnit_Framework_TestCase
{
    // State verification
    public function testState()
    {
        $stub = $this->getMock('Collaborator', array('getStories'));
        $stub->expects($this->once())
            ->method('getStories')
            ->will(new ReturnValue(array()));

        $presenter = new Presenter($stub);
        $data = $presenter->doSomething();

        $this->assertEquals(array(), $data);
    }
}

Now if you run the test it fails with the following error message:

PHPUnit_Framework_Exception: Invalid method declaration; return type required

The test also fails if the returned type doesn’t match the expected one defined in the DocBlock:

class Collaborator
{
    /**
     * @return int
     */
    public function getStories($limit)
    {
        // ...
    

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

Link
Christian WeiskePhar: Browser caching for static files (15.4.2014, 15:06 UTC)

Browsers are not able to cache static files delivered from PHP .phar archives, because Phar::webPhar() does not send out HTTP caching headers (Cache-Control, Expires).

The only way to intercept Phar::webPhar() before it delivers static CSS or JavaScript files is the $rewrites callback that may be passed as 5th parameter to webPhar().

A custom stub could look like this:

<?php
/**
 * Rewrite the HTTP request path to an internal file.
 * Adds expiration headers for CSS files.
 *
 * @param string $path Path from the browser, relative to the .phar
 *
 * @return string Internal path
 */
function rewritePath($path)
{
    if (substr($path, -4) == '.css') {
        header('Expires: ' . date('r', time() + 86400 * 7));
    }
    return $path;
}

Phar::webPhar(null, 'www/index.php', null, array(), 'rewritePath');
__HALT_COMPILER();
?>

Link
Bruno ŠkvorcImplementing Multi-Language Support (14.4.2014, 17:00 UTC)

Setting up a multilingual site may be a good way to attract new customers to your business or gain more participants in your project. Translating a simple site with a few static pages probably won’t probably be complicated, but more complex PHP web applications may require a lot of work when launching multiple language support. In this article I’ll present different types of content that need to be taken under consideration when internationalizing a site. Read on to get to know how to handle translating them into different languages.

Continue reading %Implementing Multi-Language Support%

Link
Paul M. JonesHow To Modernize Your Legacy PHP Application (14.4.2014, 14:57 UTC)

It is accomplished: “Modernizing Legacy Applications in PHP”, the book that will help you modernize your legacy PHP codebase, is complete. You can get it now it at https://leanpub.com/mlaphp.


Is your legacy PHP application composed of page scripts placed directly in the document root of the web server? Do your page scripts, along with any other classes and functions, combine the concerns of model, view, and controller into the same scope? Is the majority of the logical flow incorporated as include files and global functions rather than class methods?

If so, you already know that the wide use of global variables means that making a change in one place leads to unexpected consequences somewhere else. These and other factors make it overly difficult and expensive for you to add features and fix bugs. Working with your legacy application feels like dragging your feet through mud.

But it doesn’t have to be that way! Modernizing Legacy Applications in PHP will show you how to modernize your application by extracting and replacing its legacy artifacts. We will use a step-by-step approach, moving slowly and methodically, to improve your application from the ground up.

Moreover, we will keep your application running the whole time. Each completed step in the process will keep your codebase fully operational with higher quality. When we are done, you will be able to breeze through your code like the wind. Your code will be autoloaded, dependency-injected, unit-tested, layer-separated, and front-controlled.


From the Foreword by Adam Culp:

Developing with PHP has really matured in recent years, but it’s no secret that PHP’s low level of entry for beginners helped create some nasty codebases. Companies who built applications in the dark times simply can’t afford to put things on hold and rebuild a legacy application, especially with today’s fast paced economy and higher developer salaries. To stay competitive, companies must continually push developers for new features and to increase application stability. This creates a hostile environment for developers working with a poorly written legacy application. Modernizing a legacy application is a necessity, and must happen. Yet knowing how to create clean code and comprehending how to modernize a legacy application are two entirely different things.

But understanding how to use these refactoring processes on a legacy codebase is not straight forward, and sometimes impossible. The book you’re about to read bridges the gap, allowing developers to modernize a codebase so refactoring can be applied for continued enhancement.


Early reviews and testimonials from the feedback page:

  • “This is one of those books that PHP developers from all skill levels will be able to glean value from, and I know after just a single read-through that it will be an oft-referenced resource when I need to convert my old legacy-based procedural code into something cleaner, object-oriented, and testable.” (J. Michael Ward)

  • “As I followed the exercises in the book, my questions almost seemed to be anticipated and answered before the chapter was over. Structurally the book is very well paced. Chapters that I breezed over tended to be more useful than I thought they would be. I’ve been testing for years and I still picked up some useful tidbits about structuring my tests. Just having the step-by-step advice of an expert really made a difference.” (James Fuller)

  • “Reading through the book, it feels like you’re pair programming with the author. I’m at the keyboard, driving, and the author is navigating, telling me where to go and what to do next. Each step is practical, self-contained and moves you closer to the end goal you seek: maintainable code.” (Joel Clermont)

  • “This book helped me slay a 300k line of code giant and has allowed me to break out my shell. The refactored code has 15% code coverage for unit testing which grows every day.” (Chris Smith)


If you feel overwhelmed by a legacy application, “Modernizing Legacy Applications in PHP” is the book for you. Purchase it today and get started making your own life easier!

Link
Evert PotHawk Autentication considered harmful. (13.4.2014, 19:05 UTC)

I was asked recently to add support for Hawk to sabre/http. It kinda seemed like a fun addition, but I'm building an increasing grudge, up to a point where I've nearly lost interest.

Missing documentation

The documentation is incomplete. The author points to his own javascript-based implementation as the reference, but 1700 lines of javascript code is simply not as easy to read as a plain-english reference.

In addition, the version of the protocol (currently 2.0) appears to be locked to the javascript library, and not the actual protocol.

This means that if bugs get fixed in the javascript source, the protocol version gets a bump. Leaving us no way to figure out something changed in the protocol, unless you're willing to go through the diffs for the source.

Uses the used hostname and port as part of the signed string

The both the hostname and the port are part of the signed string, unlike alternatives like AWS authentication and Digest.

The only case where this would actually be relevant, is if there's two endpoints with identical urls, and re-uses the same keys and secrets, and a identical request on the same url would be unwanted.

The drawback is that many service don't know what url was originally being used by a client, due to the use of reverse proxies.

Now we're forced to create a mechanism where the reverse proxy sends the original host header to the client.

Could have built upon Digest auth

Digest has a lot of good things going for it, and has a great deal of overlap in features.

Hawks strengths here are that it uses a stronger hash algorithm (hmac-sha256) and unlike Digest, it there's no need for pre-flighted requests to discover the service nonce. The latter is also the author's main concern with using Digest instead, as stated in the FAQ.

An answer to that would have been rather simple though. Any server could simply hardcode and document their server-side nonce, rendering the initial negotiation optional, but still possible.

Furthermore, digest can be easily extended with new algoritms.

What to use instead?

I'd highly recommend using simply either HTTP Digest, or if you're looking for something a little bit more fancy, use Amazon's authentication header.

Some benefits:

  • They are tried and tested for many years.
  • Not a moving target.
  • Documented.
  • Easier to implement.
  • Have lots of sample implementations.

That being said, I will probably still add support to an upcoming version of sabre/http.

Link
Liip Tips & tricks for capifony deployment (13.4.2014, 12:30 UTC)

In this blog post we want to share some tips & tricks for deploying with capifony which you might find useful as well.

Upload parameters files per server

Capifony already supports the upload of a parameters.yml file to servers during the deployment. This is done globally or for each stage separately, what is already documented as a cookbook. The parameters files don't need to be in the repository, they just have to be on the machine where you run the deployment.

In our project each server requires its own license key for an external service. For that reason we need a separate parameters.yml file for each server and can't use the stages to distinguish them. To solve this problem we created a capifony task which can upload a different parameters file to each server.

First, we define the separate files for the servers.

# app/config/deploy/prod.rb
server 'server1.example.com', :app, :web, :primary => true, :parameters_file => 'production1.yml'
server 'server2.example.com', :app, :web, :primary => true, :parameters_file => 'production2.yml'

The directory of the files is set as a variable.

# app/config/deploy.rb
set :parameters_dir, "app/config/parameters"

Now comes the main part, we create a new task for uploading the file.

# app/config/deploy.rb
task :upload_parameters, :except => { :parameters_file => nil } do
  servers = find_servers_for_task(current_task)
  servers.each do |server|
    parameters_file = server.options[:parameters_file]

    origin_file = parameters_dir + "/" + parameters_file if parameters_dir && parameters_file
    if origin_file && File.exists?(origin_file)
      ext = File.extname(parameters_file)
      relative_path = "app/config/parameters" + ext

      if shared_files && shared_files.include?(relative_path)
        destination_file = shared_path + "/" + relative_path
      else
        destination_file = latest_release + "/" + relative_path
      end

      run "#{try_sudo} mkdir -p #{File.dirname(destination_file)}", :hosts => server

      capifony_pretty_print "--> Uploading " + parameters_file + " to " + server.host
      top.upload(origin_file, destination_file, { :hosts => server })
      capifony_puts_ok
    end
  end
end

This task is very similar to the one of the cookbook. We use the :except option to run this task only for servers which have the parameters_file property defined.

Then you can run the task.

  • For a shared parameters file: after 'deploy:setup', 'upload_parameters'
  • For an unshared parameters file: before 'deploy:share_childs', 'upload_parameters'

Generate parameters files per server

Instead of uploading the parameter files they can also be generated during the deployment. This can be used if you don't want to copy around files and just want to import another parameters file inside the parameters.yml. For this a slightly different task is needed.

# app/config/deploy.rb
task :generate_parameters, :except => { :parameters_file => nil } do
  servers = find_servers_for_task(current_task)
  servers.each do |server|
    parameters_file = server.options[:parameters_file]
    ext = File.extname(parameters_file)
    relative_path = "app/config/parameters" + ext

    if shared_files && shared_files.include?(relative_path)
      destination_file = shared_path + "/" + relative_path
    else
      destination_file = latest_release + "/" + relative_path
    end

    run "#{try_sudo} mkdir -p #{File.dirname(destination_file)}", :hosts => server

    capifony_pretty_print "--> Generating parameters file on " + server.host
    run "#{try_sudo} echo -e \"imports:\\n    - { resource: parameters/#{parameters_file} }\" >#{destination_file}", :hosts => server
    capifony_puts_ok
  end
end

The rest remains the same as for uploading the parameters files.

With this solution, the parameters.yml files have to be committed to the repository. We decided to do this because it makes the maintenance easier, e.g. we see the changes directly in our merge/pull requests.

Update schema with multiple entity managers

If you need an entity manager for updating the schema, which is not the default one, you can set a variable. All doctrine tasks in capifony will use this variable.

set :doctrine_em, 'custom_em'

But if you have multiple entity managers and want to update the schema for all of them, a little more work is required.

# Default entity manager
after 'deploy:create_symlink', 'symfony:doctrine:schema:update'

# Custom entity manager 1
after 'deploy:create

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

Link
Bruno ŠkvorcCan Great Apps Be Written in PHP – An Interview Series (12.4.2014, 18:00 UTC)

I read an old post, circa 2010, on the MailChimp blog a little while ago, about their experience using PHP.

It struck a chord with me, because the sentiments they shared I’ve felt myself, and heard echoed many times over the years. What are these sentiments, you may ask?

They’re the ones which infer that PHP, despite all its successes, really isn’t a true programming language. They’re the ones which intimate that, no matter how good you are, no matter what you’ve achieved, if you’re a PHP programmer, well, you’re really not a true developer, yet.

They’re the ones which suggest, or is that presuppose, that you should really become one of the cool kids developing in Ruby, Python, or Go; basically anything other than PHP. After all, what can you really do with PHP, right?

Continue reading %Can Great Apps Be Written in PHP – An Interview Series%

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