Posts tagged with "Programming"

Programmer Personality: 2020

While converting over my previous post of my Programmer Personality, I decided to do it again and see whats changed, as expected it has.

Your programmer personality type is:

DLSB

You’re a Planner..

You may be slow, but you’ll usually find the best solution. If something’s worth doing, it’s worth doing right.

You like coding at a High level.

The world is made up of objects and components, you should create your programs in the same way.

You work best in a Team.

A good group is better than the sum of it’s parts. The only thing better than a genius programmer is a cohesive group of genius programmers.

You are a liBeral programmer.

Programming is a complex task and you should use white space and comments as freely as possible to help simplify the task. We’re not writing on paper anymore so we can take up as much room as we need.

Find out what kind of programmer you are here !


Posted on August 09, 2020

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

Apache Localhost Rendering Slowly?

Slowweb-2.jpg Is your localhost taking longer than expected to load?

A possible quick fix is to edit your httpd.conf file and set 'ServerName' to 127.0.0.1:80 . This can make the difference between millisecond load times and crying while Apache tries to load.

# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
ServerName 127.0.0.1:80

Posted on November 03, 2014

Populating a Form with a dropdown (jQuery)

I thought I’d share this, maybe it’ll help somebody else. Basically this will take the value of the drop down (select) and show() that many input fields.

Javascript

$(document).ready(function(){
$("select[name=example]").change(function () {
$(".hidden_input").hide();
var cnt = $("select[name=example]").val();
while(cnt > 0) {
$(".hidden_input#"+cnt).show();
cnt--;
}
});
});

HTML/CSS

<style>
.hidden_input{
display: none;
}
</style>
<form>
<select name="example">
<option value="1">1 Guests</option>
<option value="2">2 Guests</option>
<option value="3">3 Guests</option>
<option value="4">4 Guests</option>
<option value="5">5 Guests</option>
<option value="6">6 Guests</option>
</select>
</form>
<div id="1" class="hidden_input">1<input name="former" type="text"></div>
<div id="2" class="hidden_input">2<input name="former" type="text"></div>
<div id="3" class="hidden_input">3<input name="former" type="text"></div>
<div id="4" class="hidden_input">4<input name="former" type="text"></div>
<div id="5" class="hidden_input">5<input name="former" type="text"></div>
<div id="6" class="hidden_input">6<input name="former" type="text"></div>

Posted on February 05, 2012

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

Why I am learning Perl

i-want-you-to-learn-perl.jpg

So this post may not be to everyone’s taste, its more a post to remind myself why I’ve decided to learn Perl. If anyone doesn’t know I already know PHP and Java.

Perl is a programming language, It’s Object Oriented, simple to learn and very powerful. Perl stands for: “Practical Extraction and Reporting Language” but others have come up with many more interesting and colorful names for it;

Perl is “the little language that could” it’s designed to be able to do as many tasks as possible in as little time as possible.

“A good perl program is one that gets the job done before your boss fires you.” Larry Wall, the creator of Perl.

Perl is an Interpreted language, so you don’t have to compile it like you do Java, C, C++ etc. For fast development work, that’s a godsend.

Perl has been successfully used for a lot of diverse tasks: text processing, system administration, web programming, web automation, GUI programming, games programming, code generation, bio-informatics and genealogical research, lingual and etymological research, number crunching, and testing and quality assurance.

Perl Pros

  • Cross Platform compatibility. A perl script for linux/unix will work just as well in windows and vice versa, and the only exceptions to that rule are those dictated by the operating system itself. (for example file paths are different in windows and unix.)
  • Online support. Perl has been around since the early 90’s, its exceptionally well known and thousands of tutorial and help sites abound on the internet.
  • CPAN.org, a massive collection of perl modules that can do almost anything, someone has usually done the work for you.
  • Taint mode, this helps you to write secure code by not trusting any data provided by the users until you have tested and declared it safe.

Perl Cons

  • Speed. Apparently with a very large program (Like word or something) the sheer size of it would make it extremely slow to compile at runtime.. This is the only Con I’ve found about Perl!

Posted on August 19, 2011

PyroCMS – CMS on the CodeIgnitor Framework

Update as of August 2020 - PyroCMS now relies upon Laravel.

pyro-cms.png

So lately I’ve been playing around with PyroCMS , for any of you who don’t know about Pyro, its basically an open source content management solution that iss based on the CodeIgnitor framework. What does that mean you ask?

  • MVC design pattern. (Model->View->Controller)
  • Security, Cross-Site Request Forgery protection, XSS filtering and very secure password encryption.
  • Caching, in order to achieve maximum performance.
  • Translated into 16 languages!
  • Extremely lightweight!
  • Support for modules, themes, plugins and widgets!
  • Multi – Site Manager (In Pro Version £45 )

Really it takes the pain out of making your standard websites, you’ll have an area where the client can update their website in a simple environment and thanks to ‘permissions’ you can be sure they won’t mess anything up!

Of course there is always going to be a stage when your better off without a framework, but for projects that it will work for, PyroCMS will save you a BUNCH of time!


Posted on August 14, 2011

Programmer Personality: 2009

I just took a fun test on “What is your programmer personality?” It is based of the Myers-Briggs Personality Test and has been changed to relate to your programming personality type.

Your programmer personality type is:

DLSB

You’re a Doer.

You are very quick at getting tasks done. You believe the outcome is the most important part of a task and the faster you can reach that outcome the better. After all, time is money.

You like coding at a Low level.

You’re from the old school of programming and believe that you should have an intimate relationship with the computer. You don’t mind juggling registers around and spending hours getting a 5% performance increase in an algorithm.

You work best in a Solo situation.

The best way to program is by yourself. There’s no communication problems, you know every part of the code allowing you to write the best programs possible.

You are a liBeral programmer.

Programming is a complex task and you should use white space and comments as freely as possible to help simplify the task. We’re not writing on paper anymore so we can take up as much room as we need.

Find out what kind of programmer you are here !


Posted on November 09, 2009

Google Delivers New Java-like Language: Noop

The developers over at Google have come up with Noop, a new language that runs on the Java Virtual Machine.

“Noop (pronounced ‘noh-awp,’ like the machine instruction) is a new language that attempts to blend the best lessons of languages old and new, while syntactically encouraging industry best-practices and discouraging the worst offenses,” according to a description of the language on the Noop language Website.

Noop supports dependency injection in the language, testability and immutability. Other key characteristics of Noop, according to the Noop site, include the following: “Readable code is more important than any syntax feature; Executable documentation that’s never out-of-date; and Properties, strong typing, and sensible modern stdlib.”

I suppose your thinking why another language? Google explain this:

Our experience has been that developers often create code that’s hard to test and maintain, without realizing it. On a large software project, this can create problems later on for the whole team. In analyzing this problem, we found that the root cause in many cases was language features - like globally visible state, misused subclassing, and API’s that are easily misused. Noop will try to avoid these problems.

Noop avoids these problems by being opinionated, meaning it pushes you toward using good practices while developing software. It does this by;

Noop saying Yes toNoop saying No to
Dependency injection built into the languageAny statics whatsoever
Testability - a seam between every pair of classesImplementation inheritance (subclassing)
ImmutabilityPrimitives
Syntax geared entirely towards readable codeUnnecessary boilerplate
Executable documentation that’s never out-of-date
Properties, strong typing, and sensible modern standard library

I’m still only learning Java myself, have to this year with the course. But I hope to mess around with Noop sometime soon in the future!


Posted on September 23, 2009

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

Programmers Day

programmer-comic.jpg Today, it is “The Day of the Programmer”. Since yesterday this has been made an official Russian holiday!

The day of programmer will be noted on September 13 (in 256- y the day of year), if year is bissextile - on September 12.

What is Programmers Day?

Programmer’s day is a whimsical “holiday” on the 256th day of the year celebrated mostly by computer programmers (reason: 256 = 2 to the power of 8 = the number of values representable in a byte of data).

Traditions include drinking, behaving silly, coding silly programs, mini computer games, playing with old computers, etc. Programmer’s day usually falls on September 13th; on leap years, it is September 12th.

Why the 256th Day of the year?

A byte can have 256 possible values, bytes are very important to programmers. Not because they are required for programs to work, but because the payroll system and Krispy Kreme doughnut cash registers require them.


Posted on September 13, 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