Posts tagged with "PHP"

Easy Caching with StashPHP

Frequently with PHP you are going to need to cache things, mostly expensive SQL queries, but also data you aren’t going to want to be inserting into the database on every page hit, for instance website statistics.

With PHP we have a few options to achieve this;

  • Caching with the file system .
    • Pros:
      • Works well with the Opcode cache
      • Usually the fastest method of caching for small or medium websites
    • Cons:
      • Clearing the cache can be a lot slower as you will have to recursively search through path’s and delete.
  • Caching with SqlLite
    • Pros:
      • Can be substantially faster than a full-blown RDBMS
      • All data is stored in a normal file in the host’s file system.
    • Cons:
      • Can only support one writer at a time, which can cause high file system latency, which is inconvenient if there are many clients trying to access it simultaneously.
  • Caching with APC
    • Pros:
      • Makes PHP faster for you through the so called opcode caching.
      • No special configuration required.
    • Cons:
      • Practically none
  • Caching with Memcached
    • Pros:
      • Allows machines to pool their memory together as one large memory cache, perfect for large websites.
      • Cross platform and cross RDBMS
    • Cons:
      • Stores data in the RAM, not ideal for small systems
      • Is considered to be a volatile in-memory key/value store
  • Caching with Redis
    • Pros:
      • Can act like memcached as a key/value store however it’s really a data structure server.
      • Persistence to disk, by default.
      • Values up to 512MB in size
      • Built in clustering
      • Extremely fast at everything
    • Cons:
      • The more objects you put in it, the more memory its going to use.

So as you can see there are a bunch of different systems that handle caching in arguably better or worse ways depending on how big your website is. Putting a small website on Redis is probably overkill, you might already have set up a RDBMS solution and now not want to change to a key value store etc.

This is where StashPHP comes in, you basically use the StashPHP library to cache things like so:

First you setup the driver to use, lets just use File System for the moment:

<?php
// Create Driver with default options
$driver = new Stash\Driver\FileSystem();
$driver->setOptions(array());
// Inject the driver into a new Pool object.
$pool = new Stash\Pool($driver);

Now you can setup your by wrapping the following code around your code:

<?php
// Get a cache item.
$item = $pool->getItem('path/to/item');
// Attempt to get the data
$data = $item->get();
// Check to see if the data was a miss.
if($item->isMiss())
{
// Let other processes know that this one is rebuilding the data.
$item->lock();
// Run intensive code
$data = codeThatTakesALongTime();
// Store the expensive to generate data.
$item->set($data);
}
// Continue as normal.
useDataForStuff($data);

Later on when you decide to add another cache, rather than needing to go rewrite all your caching calls etc. you can just change the setup of the drivers like so:

<?php
$subDrivers = array();
$subDrivers[] = new Stash\Driver\Apc();
$subDrivers[] = new Stash\Driver\FileSystem();
$subDrivers[] = new Stash\Driver\Memcached();
$options = array('drivers' => $subDrivers);
$driver = new Stash\Driver\Composite($options);
$pool = new Stash\Pool($driver);

This saves you a bunch of time and allows testing what suits your application best.


Posted on September 08, 2015

Being a PHP Developer in 2015

Generic coding image

This is just some thoughts on being a PHP developer in 2015.

A standard web project before used to just require you to setup a local web server, and then you’d upload to a standard web host with some worries about PHP versions perhaps but little to no thought required for the server side of things.Frameworks were a new thing, CodeIgniter was (to me at the time) the best thing to happen to PHP, introducing me to PHP MVC patterns, easily integrated vendor libraries (I never got into Zend Framework) and Twig .

Now a web project involves using programs such as Composer, Bower and Grunt just to manage project dependencies. Then you have PHP & JS frameworks like Symfony , Laravel, AngularJS that have really made life so much easier for us developers. Of course this all comes at a cost of having to put in time into learning all these new frameworks and tools, but the benefits of doing so are just amazing; development time goes way down and you create much better products. I wish I could further go into the benefits of each but they all require posts of their own to really get across their individual uses, I’ll attempt to get to that!

Working with UNIX servers is pretty standard for most web developers now, myself included. I’ve been using DigitalOcean for all my hosting, they really are a great host and I recommend them to anyone searching. Anyway a tool I found lately for server management which I guess is what has caused this post is Ajenti , before this I was using ISPConfig for the aim of being able to manage my servers easier than via ssh, however I found it’s interface pretty clunky and just overall slow, always ending up in ssh. After testing Ajenti in a fresh droplet I changed completely over to it on my other servers, so far it’s been amazing, I’m still using ssh here and there but overall Ajenti has really solved my problem so thanks guys. The install was amazingly simple too I recommend anyone looking for a GUI for their server to check it out.

So there seems to be a lot more to PHP web development now in 2015 than there was just a few years ago, though I personally feel all of it is for the better, making my life easier. It makes me wonder what it will be like in another few years though, whats next?


Posted on January 27, 2015

WordPress – Shortcode in PHP files

So in WordPress with plugins etc. you end up using shortcode in posts to keep things simple, an example would be if you want to display a gallery you would just use:

[galleries id="1"]

However trying to this when your outside of the “WordPress Loop” (in your theme files usually) you will hit the problem that WordPress won’t parse the shortcode.

The solution is very simple, just append the following to your shortcode:

echo apply_filters('the_content', '[galleries id="1"]');

And it works!

To read up more on shortcodes in WordPress click here .


Posted on September 11, 2011

Learn PHP: Includes & Requires

Continuing on from Learn PHP: Ifs & Elses, we can start learning about including other files, which is very helpful for things like sidebars on your website etc.

Include and Require include a file within another PHP script. There are four ways of doing this:

<?php
include();
include_once();
require();
require_once();

Now using them is simple. Lets say you have a file called “sidebar.php” with your links? All you have do do is the following:

<?php
include('sidebar.php');

One thing to remember is how to traverse directories in PHP. For instance, if my file “sidebar.php” is in a folder called “includes” you could go:

<?php
include('includes/sidebar.php');

Or another approach, if my file “sidebar.php” is in the parent directory, you could go:

<?php
include('../sidebar.php');

Now why are there four different ways to include?

Include and Require are practically the same, apart from the way they give out errors. Include will continue parsing your script and just log an error. Require however will stop the whole script to give you an error. Really it’s all down to what you want.

include_once and require_once only allow you to include the file once. This is not only more secure but stops from errors where the file was just included and variables were overwritten halfway through the script. Again they give out the same errors as include and require.

So lets go over one of each!

<?php
include('sidebar.php');
include_once('sidebar.php');
require('sidebar.php');
require_once('sidebar.php');

Posted on September 16, 2009

Learn PHP: Ifs & Else's

Continuing on from Learn PHP: Output And Operators, we can start learning about control statements which will make up the logic of your code.

Here is one in action:

<?php
$condition = true;
if ($condition) {
echo 'condition is true';
}

Simple enough to understand? First we are setting a variable $condition to = true. Then we test if that variable equals true, if so it will output anything within the curly brackets, in this instance it will output the statement condition is true.

Now if statements don’t seem on their own! What you really want is if / else statements. Setting up a similar example to the above, but with a number stored in the variable:

<?php
$condition = 10;
if ($condition == 5) {
echo "condition is 5";
}

Here the variable is set to 10. PHP Checks if it is 5. As we all know 10 is not 5, so PHP does nothing.

However in this statement, we add some more checks using the else if and else control words:

<?php
$condition = 10;
if ($condition == 5) {
echo "condition is 5";
} else if ($condition < 5) {
echo "condition is less than 5";
} else {
echo "condition is $condition";
}

In the above if the condition is 5, PHP will output that it is 5. It then checks to see if the condition is less than 5, and outputs if that is the case. Lastly, if it doesn’t match anything else it outputs what the condition is. So in this instance we would get the output condition is 10

One last example using strings just to highlight that they can also make use of this functionality:

<?php
$condition = "yes";
if ($condition == "no"){
echo "condition is false";
} else if ($condition == "yes"){
echo "condition is true";
} else {
echo "Something happened to the variable";
}

Here you can see that the condition is actually a word. PHP checks it just like it would a number and outputs all the same. Here PHP would output condition is true.

You can now move onto the next part Learn PHP: Includes & Requires


Posted on August 28, 2009

Learn PHP: Output & Operators

This series was severely outdated, as it was originally written in 2009, I have updated it with more modern options as of 12th July 2020

Continuing on from Learn PHP: Setup, we can start with a few of the basic principles / building blocks of the language.

Output

The first thing you want to be able to do is output data to your console, we can do this by using the echo statement.

<?php
echo "hello world";

Comments

Comments are multipurpose they allow you to temporarily cause code not to run as well as make notes describing code functionality.

PHP supports two different ways of commenting, C/C++ style and Unix shell style (Perl Style). We will focus on C/C++ style here.

Example’s of echo via C++ Style are as follows:

<?php
// Comments starting with this are single line.
echo "hello";
/* Any comments within this combination of symbols
can span multiple lines
*/
echo "world";

You can also use comments to temporarily cause a block of code to no longer run. In the example below the console won’t output anything.

<?php
/**
echo "hello world";
*/

Variables

You will use variables for a variety of things when programming. Essentially they let you store some data to either use or modify later on.

Here are two examples of variables, one containing a string, the other an integer.

<?php
$first_variable = "Variable One";
$second_variable= 1;

Operators

There are a number of operators you can use within PHP.

Arithmetic Operators

There are plenty of arithmetic operators for operating on numbers.

Here are an example of a few of the basic ones you’ll use frequently.

<?php
$add = 2 + 1;
echo $add; // Will output '3'
$subtract = $add - 1;
echo $subtract; // Will output '2'
$multiply = $add * 4;
echo $multiply; // Will output '8'
$divide = $multiply / 2;
echo $divide; // Will output '4'

String Operators

There are two string operators available in PHP. You’ll use these for joining strings together like below:

<?php
$variable = "Hello";
echo $variable . " world"; // Will output 'Hello world'
$variable .= " world";
echo $variable; // Will now output 'Hello world'

You can now move onto the next part Learn PHP: Ifs And Else’s


Posted on August 20, 2009

Learn PHP: Setup

This series was severely outdated, as it was originally written in 2009, I have updated it with more modern options as of 12th July 2020

Cloud based options

There are plenty of free cloud based editors that will allow you to get up and running without having to install anything on your computer. If you are just looking to try out PHP and aren’t sure you will continue using it, this is the best option.

Windows options

Wamp

Wamp is a GUI installer that will guide you through installing a web server Apache a database mySQL, the PHP programming language and PhpMyAdmin which allows you to easily manage your databases.

If you are looking for an option for more long term use, this is the option I would suggest.

Xampp

Xampp is another GUI installer, made by Apache. It will install a web server Apache, a database MariaDB and two programming languages PHP and Perl.

PHP Built-in web server

As of PHP 5.4 there is now a built-in web server available in PHP.

This means that you can now just go here and download the latest “Non Thread Safe” archive. You should then extract the archive to somewhere (eg C:\php) and then add that directory to your path as explained here.

This Stack Overflow answer contains answers that explain in detail the differences between “Thread Safe” vs “Non Thread Safe”.

OSX options

For Mac OSX the only easy option I’m aware of is installing via Homebrew, if you don’t already have Homebrew, it is a package manager that if you are getting into development you will want to have installed.

Once Homebrew is installed you can just run the following to install php.

brew install php

Linux options

If you are using Linux, you are going to need to utilise a search engine in order to get setup. Digital Ocean have good walkthroughs like this one for Ubuntu 18.04.

You can now move onto the next part Learn PHP: Output & Operators


Posted on July 07, 2009