Building an Array Object Class

 –  Comments Off on Building an Array Object Class

Having spent several years now working with the excellent Laravel platform, one of the features I tend to miss the most on non-Laravel projects is the Collection class. Sometimes I end up building my own, or going in search of some similar solution built by someone else, but today I thought I would demonstrate how someone might build an array manipulation class for themselves.

You should be somewhat familiar with the basic concept of PHP classes and objects since this lesson will make extensive use of class methods. But, if you aren’t familiar with them, maybe this lesson can help you understand the power that they can hold.

So, with no further introduction, let’s dive right in.

Building The Initial Class Structure

Our objective today is to create a simple class that will accept a PHP array during construction and then allow us to perform some basic manipulations of the data within that array. Let’s start by creating a brand new file which will have the same name as our array manipulation class. I’m going to call mine ArrayObject so I will create a new file called ArrayObject.php and start building a new PHP class inside it.

<?php 
namespace WarkenSoft\SimpleArrayObject;
class ArrayObject
{
    // we will add more here later...
}

You may notice right away that I have given a namespace to this class. I won’t go into detail on the idea of namespaces at this time, but suffice to say it’s a good idea to namespace your packages, especially if they will be used in situations where more than one person will be contributing code. Maybe another day I’ll write up an article about namespacing.

Now, with the code above we have created a simple class definition. It doesn’t do anything yet, but it defines how instances of our class will function. If I was intending to create an instance of the class, I could do it as follows:

<?php
use \WarkenSoft\SimpleArrayObject\ArrayObject;
$myClassInstance = new ArrayObject();

So, now we can start building our methods for the class. First off, we should allow people to actually initialize it with an array of data. To do this, I prefer to give a few different ways of initializing instances of the object.

<?php 
namespace WarkenSoft\SimpleArrayObject;
class ArrayObject
{
  private $data = [];

  public static function Make( $data = [] )
  {
    return new static($data);
  }

  public function __construct( $data = [] )
  {
    $this->data = $data;
  }
}

At first glance, this may seem a little intimidating, but don’t worry, I’ll walk through it with you. All we are doing here is providing some specific ways in which the class can be initialized. I specifically wanted to make it so that people can pass in an array of data when they created an instance of the class, and that the data would be stored inside the class itself.

Lets look first at the __construct method. This is kinda a special method that is run automatically by PHP when a new instance of the class is built. I have told it to expect to receive an array of data, and I have also preset it with a default value of an empty array. So, if no data is given to it, the class will still initialize but with an empty array. The __construct() method then takes the $data variable and simply assigns it to a private, internal class variable called $data which I had already initialized.

Now look at the Make() function. You will notice that this function is defined as being “static” which means (among other things) that it can be run directly on the class definition, rather than having to run it on an instance of the class. It then simply returns a new instance of this class, passing in the $data variable it was given. At the end of the day, it means you can create a new instance of this class like this somewhere else in your code.

<?php
use \WarkenSoft\SimpleArrayObject\ArrayObject;
$my_array_data = [
  'Thing One',
  'Thing Two',
  'Thing Three',
];
$myArrayClassInstance = ArrayObject::make($my_array_data);
// ... OR ...
$myArrayClassInstance = new ArrayObject($my_array_data);

This now gives us the basics of a simple class that will store the data we give to it. Probably the next most important step will be to pull the data back OUT of the class. There is a way to make classes like this iterable so that you can use the in very similar ways to arrays, but for the sake of keeping things simple, I am just going to add a method onto the class that allows us to retrieve the stored data. We will add the following function to the bottom of our class.

public function items() {
  return $this->data;
}

As I’m sure you can guess, calling this function simply returns the contents of $data back to you for however you want to use it. You would call it like this…

$my_new_array_data = $myArrayClassInstance->items();

Now we finally have the basics we need in order to begin adding useful features to manipulate the array. If you are familiar with classes and objects in PHP, this all should be quite simple and straightforward to you. So far, this is a lot of code to hold an array, and not really do anything much with it. However, in the next portion we will begin adding functions to give this class it’s true power.

Our next step will be to add something that actually manipulates the array data.

Mapping The Array

In order to make almost any change to the data of the array itself, we’re going to use PHP’s array_map() function. This function accepts two parameters. One is a callable function that actually performs the change of the array data, the other is the array itself. Though we could use this array_map() function directly in our code, it’s more elegant to build it into our class and be able to use it in-line with other array manipulation methods. To implement it, we will add the following function to the bottom of the ArrayObject class.

public function map( callable $callable )
{
  return new static( array_map($callable, $this->data) );
}

This method is really quite simple but REALLY powerful. It receives a callable as it’s parameter, runs it and the current array data through PHP’s array_map() function and returns a brand new instance of our class containing the results.

We can use it in the following way:

$my_array = [
  'thing one',
  'thing two',
  'thing three',
];
$capitalized_array = ArrayObject::make( $my_array )->map( function ( $item ) {
  return ucfirst( $item );
} )->items();

So, we initialize a new copy of ArrayObject with $my_array. We run the map() function and pass to it an anonymous function in which we capitalize the first word of each item. Then we retrieve the new array data with items().  When printed out, $capitalized_array contains the following:

Array
(
    [0] => Thing one
    [1] => Thing two
    [2] => Thing three
)

The key here is the callable that we are passing into the map function. If you are unfamiliar with callables, you can read more abut them on the PHP site. Essentially what happens though is we send an anonymous function through to the map() function which expects to receive a single item from the array, performs our changes, and returns the result. The array_map() then goes through each item of the array, passes that item into our function, and builds a new array based on all the results we send back.

Simple Capitalization

If capitalizing the items in an array is something you do often, you may want to incorporate that right into your ArrayObject class. You could do that quite easily by adding the following method to it:

public function capitalize()
{
  return $this->map( function ( $item ) {
    return ucfirst( $item );
  });
}

Now, in each situation where you might have a list of things to capitalize, you can simply use your ArrayObject like this:

$capitalized_array = ArrayObject::make( $original_array )->capitalize()->items();

Are you starting to see the power that this type of tool can offer you?

Wrapping Up

I intend to write a follow-up to this post, where I explore some other features you can incorporate into your ArrayObject, but for now I think this post gives you a good start. You should be able to follow the example set forward in the capitalization method above and build all sorts of useful array manipulation tools that you might need. Doing so in a class like this allows you to string them together in a very easy-to-read fashion that you can re-use time and again. For example, you might figure out how to do something like this:

$original_array = [
  'thing one',
  'thing two',
  'thing three',
];
$result = ArrayObject::make( $original_array )
                     ->appendWord('mississippi')
                     ->removeWord('thing')
                     ->capitalize()
                     ->items();

I trust this lesson has been valuable to you. If you have questions, please don’t hesitate to ask. For your reference, here’s the full class we created today.

<?php

namespace WarkenSoft\SimpleArrayObject;

class ArrayObject
{
  private $data = [];

  public static function Make( $data = [] )
  {
    return new static($data);
  }

  public function __construct( $data = [] )
  {
    $this->data = $data;
  }

  public function items()
  {
    return $this->data;
  }

  public function map( callable $callable )
  {
    return new static(  array_map($callable, $this->data) );
  }

  public function capitalize()
  {
    return $this->map( function ( $item ) {
      return ucfirst( $item );
    });
  }
}

All the best until next time.

Related Reading:

Php: Learn PHP In A DAY! - The Ultimate Crash Course to Learning the Basics of PHP In No Time (Learn PHP FAST - The Ultimate Crash Course to Learning ... of the PHP Programming Language In No Time)Php: Learn PHP In A DAY! - The Ultimate Crash Course to Learning the Basics of PHP In No Time (Learn PHP FAST - The Ultimate Crash Course to Learning ... of the PHP Programming Language In No Time)PHP Programming Language Are You Ready to Know All About PHP? Today only, get this Kindle Book for just $8.99. Regularly priced at $11.99. Read on you... Read More >
Plug-In PHP: 100 Power Solutions: Simple Solutions to Practical PHP ProblemsPlug-In PHP: 100 Power Solutions: Simple Solutions to Practical PHP ProblemsPractical solutions to real-world problems
This practical guide gives you 100 ready-to-run PHP functions for solving most of the main problems you ... Read More >
Programming PHP: Creating Dynamic Web PagesProgramming PHP: Creating Dynamic Web Pages

This updated edition teaches everything you need to know to create effective web applications with the latest features in PHP 5.x. You’ll start w... Read More >

Filed in: Code Snippets, PHP Programming

Comments are closed.