PHP ClassesReview: Symfony Certification (28.7.2015, 04:41 UTC)
Symfony Certification
Title
Reviewer
Joseluis Laso
Category
PHP books
Publisher
Leanpub
Author
Raúl Fraile
Summary
Symfony Certification self-study is a well structured book, if can say, following all the subjects proposed by SensioLabs in their official site.

Like the author, I was in the same certification exam, getting so nervous but having a great desire of learning from that experience.

Years later and after having worked intensively in several Symfony2 projects, I still remember how scared I was looking at those questions in front of the very own Fabien Potencier.

Now that I finished this book review, I am looking forward to get my hands dirty and read each of the more than 250 questions and their detailed explanations.

This time I have the goal that I will be able to get the Symfony certification, without doubts, much better prepared when compared with the last time I tried it years ago.
Link
SitePoint PHPSpeeding up Existing Apps with a Redis Cache (27.7.2015, 16:00 UTC)

We’ve gone through the basics of Redis in PHP before, but it’s time to cover a real life use case. In this tutorial, we’ll add it to an already deployed application to give the app the appearance of speed.

Redis Logo

You can easily follow along by cloning the 0.6 release of the app.

The Problem

Before applying a solution, we need to have a clear definition of the problem.

The application in question, when executing a query, runs off to Diffbot’s API and makes it query the dataset. The subset is then returned and displayed. This can take up to 5 or so seconds, depending on the busyness of Diffbot’s servers. While the situation will undoubtedly improve as they expand their computational capacity, it would be nice if a query executed once were remembered and reused for 24 hours, seeing as the collection is only refreshed that often anyway.

“But what good is caching a single query?” you might wonder. It’s not like most people will search for one and the same thing often.

Well… as a matter of fact, not only has research shown that they will often search for one and the same thing (React is trending? Sudden influx of “react” queries), they will also very reliably search for prolific authors (or themselves). Considering the fact that implementing this cache costs us literally nothing (and actually reduces costs by reducing strain on the servers), adding it in is an easy win, even if it weren’t used as often as one would hope. There is no reason not to add it - it can only benefit us.

With the problem clearly defined, let’s handle the prerequisites.

Continue reading %Speeding up Existing Apps with a Redis Cache%

Link
PHP ClassesHow to Render 3D Surfaces in PHP using 2D Contour Plots (27.7.2015, 07:32 UTC)
By Dan Thanh
Contour plots are graphics that render lines that connect points in a geographic region that have the same value, for instance points in a terrain with the same altitude. They are useful for instance to represent 3D features of a terrain in a 2D image.

Read this article to learn more about contour plots and how to render them using the PHP Contour Plot package.
Link
Michelangelo van DamSpeeding up database calls with PDO and iterators (26.7.2015, 14:14 UTC)
Image source: Wikipedia.org
When you review lots of code, you often wonder why things were written the way they were. Especially when making expensive calls to a database, I still see things that could and should be improved.

No framework development

When working with a framework, mostly these database calls are optimized for the developer and abstract the complex logic to improve and optimize the retrieval and usage of data. But then developers need to build something without a framework and end up using the basics of PHP in a sub-optimal way.

$pdo = new \PDO(
$config['db']['dsn'],
$config['db']['username'],
$config['db']['password']
);

$sql = 'SELECT * FROM `gen_contact` ORDER BY `contact_modified` DESC';

$stmt = $pdo->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll(\PDO::FETCH_OBJ);

echo 'Getting the contacts that changed the last 3 months' . PHP_EOL;
foreach ($data as $row) {
$dt = new \DateTime('2015-04-01 00:00:00');
if ($dt->format('Y-m-d') . '00:00:00' < $row->contact_modified) {
echo sprintf(
'%s (%s)| modified %s',
$row->contact_name,
$row->contact_email,
$row->contact_modified
) . PHP_EOL;
}
}
Above example code is a most common way to retrieve data. At first sight, this code is clean and looks good, but looking more closely you will discover a couple of points to improve.

  • Above code is not reusable, so whenever you need a similar functionality you're stuck with duplicating existing code.
  • Even though you're fetching an object with $stmt->fetchAll(\PDO::FETCH_OBJ); you still face the issue you're using an array of objects which will consume too much memory when fetching lots of data.
  • Filtering is done within the routine, which also means that if you have other filtering conditions you need to modify existing logic, making it hard for maintenance and expanding functionality.

Iterators

Most of the modern frameworks are using Iterators for their data retrieval, because they're fast and reusable. But also they allow other Iterators to filter and modify the retrieved results. Building an application without a framework still gives you the option to use Iterators as they're part of PHP since Version 5.0.0 Beta 2.

So lets assume you continue to use PDO for your data retrieval, we can choose between two options:
  1. Use PDOStatement::fetchAll() to retrieve all data in a single go
  2. Use PDOSTatement::fetch() to retrieve a single row per iteration

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

Link
blog.phpdevCustom Callbacks with Invoke (26.7.2015, 12:59 UTC)

In putting the Invoke library to use I noticed something. While I could tell it to check for groups and permissions on the current user and limit HTTP methods on the request, there were more complex things I needed to check that weren’t part of these defaults. Now, I could just extend invoke to include match types for everything I needed (injecting a custom match class based on my needs) but I wanted something a bit more generic that I could use to call my own logic and return the pass/fail result.

So, I added in the “object.callback” match type that allows you to call a static method in your own code and perform the evaluation yourself. Here’s how it works. Say you have this configuration in your routes.yml file:

/foo:
  protected: on
  callback: \App\MyUser::test

This tells Invoke that when the user requests the /foo URL, the protection should kick in. It then goes into the checks portion of the process. This sees the special callback option and looks the class and method to call. In this case, we’ve told it to try calling the test method \App\MyUser. This class needs to be autoloadable so that Invoke can directly call it and its static method. Yep, that’s right – it needs to be a static method but you’ll be provided with everything about the request in the incoming $data variable. Here’s what the method should look like:

public static function test(\Psecio\Invoke\Data $data)
{
  /* perform your evaluation here and return a boolean */
}

In the $data variable there, you’ll have access to the context of the application via some object properties:

  • user: The current InvokeUser instance (ideally where your user lies too)
  • resource: The resource that was requested (includes access to the requested URI)
  • route: This is the route match from Invoke’s configuration the current request matches. This contains the route regex match, the configuration options and any additional parameters passed along

For example, say you needed to get the parameters from the request to do further evaluation. You could fetch them through $data->resource->getParams() and get the associative array back.

Adding these callbacks makes the Invoke system a lot more flexible and allows you to create those custom match types without having to have whole other classes just to perform your checks.


Link
SitePoint PHPConsole Wars – PHP CLI Libraries (25.7.2015, 16:00 UTC)

I have always been a big fan of console commands and I try to provide a command line interface (CLI) as much as possible in most of my PHP projects. In this article, I’ll briefly compare three PHP console command libraries: The Symfony console component (symfony/Console) The Hoa console (hoa/console) The Webmozart console (webmozart/console) Origin […]

Continue reading %Console Wars – PHP CLI Libraries%

Link
Official Blog of the PEAR Group/PEAR PresidentPEAR 1.10.0dev1 brings PHP 7 compatibility! (25.7.2015, 13:36 UTC)

We’ve released PEAR installer version 1.10.0dev1, which brings support for PHP 7 while dropping support for PHP 4 – 5.3.

See the announcement post @ cweiske.de for more information.

Link
Christian WeiskePEAR 1.10.0dev1 brings PHP 7 compatibility! (25.7.2015, 11:50 UTC)

The new PEAR installer release adds PHP 7 support while dropping support for PHP 4 - 5.3. It also fixes a nasty SSL issue that made it hard to use on PHP 5.6. With the update, strict warnings about static calls to a non-static PEAR::isError() are a thing of the past.

I've just published the first preview version: PEAR 1.10.0dev1.

You can upgrade your existing PEAR version with the following command:

$ pear upgrade PEAR-1.10.0dev1

Pre-release versions of go-pear.phar and install-pear-nozlib.phar can be temporarily be found at

Please report any bugs you find on the PEAR bug tracker or on the pear-dev mailing list.


I'm looking for a new job. If you can recommend a company in Leipzig/Germany that's looking for a PHP developer, please drop me a mail.

Link
Simon HolywellSQL style guide (24.7.2015, 11:37 UTC)

When you’re working in a team you need ways to easily share and denote good style and taste. This is true of your primary programming language with PEP8 for Python and PSRs 1 & 2 for PHP being well known. There is probably even a style guide for HTML and CSS set out at your company. So why should SQL miss out on the party?

I have written a style guide for SQL to promote a consistent code style ensuring legible and maintainable projects - sqlstyle.guide.

SELECT a.title, a.release_date
  FROM albums AS a
 WHERE a.title = 'Charcoal Lane'
    OR a.title = 'The New Danger';

There are so many variant SQL styles that projects and people use which can make code difficult to easily read. Looking over various questions on Stackoverflow (on of which was mine!) I noticed that there were elements of good style that were shared by most examples.

I figured it was time that SQL had a concise and easy to read style guide that could easily be adopted and/or modified for bespoke requirements.

It is trivial to apply this style to your projects now or going forward. In the case of PHP you could have some code like the following.

$year = filter_input(INPUT_GET, 'year', FILTER_SANITIZE_NUMBER_INT);
$db = new PDO(
    'mysql:host=localhost;dbname=testdb;charset=utf8',
    'username',
    'password'
);
$statement = $db->prepare("
SELECT r.last_name,
       (SELECT MAX(YEAR(championship_date))
          FROM champions AS c
         WHERE c.last_name = r.last_name
           AND c.confirmed = 'Y') AS last_championship_year
  FROM riders AS r
 WHERE r.last_name IN
       (SELECT c.last_name
          FROM champions AS c
         WHERE YEAR(championship_date) > :year
           AND c.confirmed = 'Y');
");
$statement->bindParam(':year', $year, PDO::PARAM_INT)
$statement->execute();
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);

To produce the guide I settled upon using GitHub Pages, Jekyll and Markdown sources. This means it is very easy to make forks, open issues and pull requests as GitHub Pages will handle the hosting and site build process. It is released under the Creative Commons Attribution-ShareAlike 4.0 International License.

The style in this guide is explicitly designed to be compatible with Joe Celko’s book SQL Programming Style so that teams who have already read that book will find the guide easy to adopt.

To read the guide you can simply visit sqlstyle.guide and to access the sources you can find the repository on GitHub.

If you like the guide please consider sharing it with your team and via twitter - thanks!

Link
Lorna MitchellTest Your PHP Application on PHP 7 (24.7.2015, 10:52 UTC)

PHP 7 is coming, which is nice, but what does it mean for the majority of PHP developers? PHP as a community is notoriously slow in adoption, some of us are still waiting for 2012's new shiny to be available as standard on our hosting platforms. However with the performance benefits and a few really nice new features, PHP 7 is well worth everyone's attention, and it's actually quite easy to get started so here's my quick howto.

Get A PHP 7 Platform

These examples use Rasmus' php7dev box because it's self-contained so it won't affect any other part of your setup, and because it's super-simple to get started with on any platform. It's a vagrant box running Debian 8 and with a really easy way of switching PHP versions, including 7. Multiple PHP versions is super handy because then you can very easily check if your PHP 7 bug really is a PHP 7 bug or if it was there on PHP 5.6 as well.

To get a new project set up you need to make the files available in the PHP 7 VM, and set up an nginx server block (equivalent of a virtual host) to point to it. If your project needs storage behind it, you can either connect to those on your host machine, or the VM has MySQL and PostgreSQL already installed.

Mount Your Project As A Shared Folder

Do this step before booting the virtual machine (or just vagrant halt). Add a line to Vagrantfile to tell the VM to share another folder:

    config.vm.synced_folder "/home/lorna/projects/joindin", "/vagrant/joindin"

I added mine immediately before the end at the bottom of the file - the first directory path is where it is on my laptop, and the second is where it will be in the VM. Now when you vagrant up and SSH in (vagrant ssh from the same directory as the Vagrantfile), you should see your directory is there with the files present.

Configure Nginx

While I mostly use Apache with mod_php, this box defaults to using nginx and it's easy to set up even if you haven't used it before. All we need to do is create a new file in /etc/nginx/conf.d, and add something like (there's a lot of this, I obviously copy/pasted the starting point from somewhere but I'm pretty sure it has everything that most applications need so try it):

server {
    listen       80;
    server_name  api.joindin.php7;
    root   /vagrant/joindin/joindin-api/src/public;
    index  index.php;
    access_log  /var/log/nginx/default-access.log  main;
    error_log   /var/log/nginx/default-error.log;

    error_page   500 502 503 504  /50x.html;

    location = /50x.html {
        root   /var/www/default;
    }

    location / {
        try_files $uri $uri/ @rewrite;
    }
    location @rewrite {
        rewrite ^(.*)$ /index.php;
    }

    location ~ \.php {
        include                  fastcgi_params;
        fastcgi_keep_conn on;
        fastcgi_index            index.php;
        fastcgi_split_path_info  ^(.+\.php)(/.+)$;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_intercept_errors on;
        fastcgi_pass unix:/var/run/php-fpm.sock;
    }
}


Edit your server_name and root settings as appropriate, then restart nginx with:


sudo service nginx restart

At this point, the VM is ready but our host machine (in this case my laptop) doesn't know where to send the traffic.

Set Up Your Host File

The VM will by default have an IP address of 192.168.7.7 and hopefully you know where your hosts file is. I'm on Ubuntu so mine is /etc/hosts and I just need to add one line to it:


192.168.7.7 api.joindin.php7

You should now be able to hit your chosen hostname from your browser and see your PHP application working (or not). Error logs are in /var/log/nginx, and as I say, it's worth switching back to PHP5.6 (by running newphp 56 - then you want newphp 7 to switch back later) to check if the problem is actually PHP 7 or if you set something else up wrong.

If you have test suites, please run them, and put your application through its paces. Any bugs you find, try to narrow down the replication case and report them to the appropriate place - this might be your team, but could just as easily be a library, a framework, or PHP itself. The only way to get PHP and its ecosystem as good as it can be before it goes stable is for all of us to do with it before release all the things we'll want to do after!

Getting Going With PHP 7

Hopefully this gave you a quick-start on a very easy pla

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

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