BLOG

A blog about PHP development, Zend Framework and Linux.

 


 

RjhRedbean has been bumped to v2.0

Posted by richard on May 21, 2013

I have been using RjhRedbean for a while now and over time my version has been cleaned up and simplified. Today I pushed this version of RjhRedbean to Github and packagist and tagged it as v2.0.

The original RjhRedbean is still available and has been tagged as v1.0.

If your composer.json is configured to install "dev-master", you will find that RjhRedbean gets updated next time you run a composer update. There is a backwards compatability break since I have fixed the namespaces in v2.0.

If you find things break you have two choices:

Either change the settings in config/application.config.php as detailed in https://github.com/richardjh/RjhRedbean/blob/master/README.md
Or if you prefer not to have to make changes, you can still use the original module by setting "richardjh/rjhredbean": "v1.0" in your composer.json

If you find any problems, please feel free to email me at richard@richardjh.org.


Domain Renewal Group

Posted by richard on March 12, 2013

Today I received a letter from the Domain Renewal Group.

Domain Renewal Group

 

Now hands up if you think this is a bill. It looks like a bill right? It appears form this letter that I need to pay them some money for domain renewals, right?

Do a Google search for "Domain Renewal Group" and you and find many people complaining about this scam. People are angry and some people may even transfer domains to them without fully understanding what is going on. People have been tricked by a scam.

Have they? Really?

What Domain Renewal Group is doing here is to try to get people to transfer their domains to them. I have read the letter. It is clearly written.

Here is a list of the points in the letter:

 

1. As a courtesy to domain name holders, we are sending you this reminder that your domain name registration is due to expire in the next few months.

2. When you switch today to the Domain Renewal Group, you can take advantage of our best savings.

3. Your registration for : yourdomain.com will expire on July 9, 2013.

4. Act today!

5. Registering your name with us will ensure you retain exclusive rights to it on the Web,

6. and now is the time to transfer and renew your domain name from your current Registrar to the Domain Renewal Group.

7. Failure to renew your domain name by the expiration date may result in a loss of your online identity making it difficult for your customers and friends to locate you on the Web.

8. Privatization of Domain Registrations and Renewals now allows the consumer the choice of Registrars when initially registering and also when renewing a domain name.

9. Domain name holders are not obliged to renew their domain name with their current Registrar or with the Domain Renewal Group.

10. We would like you to transfer and renew your name from your current Registrar

11. review our prices and decide for yourself.

12. Your are under no obligation to pay the amounts stated below, unless you accept this offer.

13. This notice is not a bill.

14. it is rather an easy means of payment should you decide to switch your domain name registration to the Domain Renewal Group.

 

You see when it is spelt out and you can read the words instead of jumping to the wrong conclusion, the information here is clear and factually correct. In fact it makes it far clearer than my current hosting provider does, they simple renew my domain without ever explaining points 8 and 9.

Point 13 is even in bold, This notice is not a bill

I have noticed a growing trend that people generally always try to assign blame to others. There is always a reason it is someone elses fault.

That is what this post is really about. It has nothing to do with Domain Renewal Group really.

The point is if you aren't able to read 14 clearly written sentences and make up your own mind, the real problem is not with misleading marketing strategies, the problem is with you.

Just watch an advert break on TV. Does MacDonalds really provide a healthy choice or an environment where people go for coffee and a chat? Does Coke really contribute to a healthy balanced diet? Does Lynx really make girls fall from the sky? Will buying a lottery ticket really get you a boat?

Like point 11 says, decide for yourself.


Controlling an Arduino from my computer

Posted by richard on March 4, 2013

Last year I was contracted to program a some Siemens LOGO! devices that are now used in a few locations to control water treatment plants. Whilst it was fun to work with logic controllers again, the software is very expensive and the devices are not really suitable for playing with.

At Christmas I was bought an Arduino Uno and last week I finally got around to buying a Starter Kit for Arduino (ARDX) from .:oomlout:. What I love is that the Arduino lets you interface software and real life objects so simply and for so little money.

To make a start, I have put together a simple proof of concept for controlling LEDs from my netbook over a serial interface.

Here is the breadboard layout

You will need to alternate green and red LEDs for r and g to work correctly. Red LEDs should be connected to pins 2,4,6,8 and green LEDs connected to pins 3,5,7,9.

This code will need to be compiled and uploaded using the Arduino IDE.

/* leds controlled over serial
 *
 * Richard Holloway
 * https://github.com/richardjh/leds-controlled-over-serial
 *
 * A simple proof of concept that allows you to control LEDs using your computer
 * 
 * 0 - turn off all LEDs
 * 1 - turn on all LEDs
 * 2 - turn on LED on pin 2
 * 3 - turn on LED on pin 3
 * 4 - turn on LED on pin 4
 * 5 - turn on LED on pin 5
 * 6 - turn on LED on pin 6
 * 7 - turn on LED on pin 7
 * 8 - turn on LED on pin 8
 * 9 - turn on LED on pin 9 
 * g - turn on all green LEDs
 * r - turn on all red LEDS
 *
 * There is also a physical button that turns on all LEDS on pin 10
 * and the RESET button will turn off all LEDs as it resets the program
 */
 
String inChar = "";
int    pin;
int    val = 0;
int    button = 0;
 
// Setup runs once when the program starts
void setup() {
  Serial.begin(9600);
  pinMode(2,OUTPUT); 
  pinMode(3,OUTPUT); 
  pinMode(4,OUTPUT); 
  pinMode(5,OUTPUT); 
  pinMode(6,OUTPUT);  
  pinMode(7,OUTPUT); 
  pinMode(8,OUTPUT); 
  pinMode(9,OUTPUT); 
 
  pinMode(10,INPUT); 
}
 
// Loop runs over and over
void loop() {
   button = digitalRead(10);
   if ( button == 0 ) {       // Button has been pressed, turn on all LEDs
      digitalWrite(2,HIGH);
      digitalWrite(3,HIGH);
      digitalWrite(4,HIGH);
      digitalWrite(5,HIGH);
      digitalWrite(6,HIGH);
      digitalWrite(7,HIGH);
      digitalWrite(8,HIGH);
      digitalWrite(9,HIGH);
    }
}
 
// SerialEvent is run each time loop runs and data is received on RX
void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read(); 
 
    if ( inChar >= 50 && inChar <= 57 ) { // 50 is ascii for 2, 57 is 9
      pin = inChar - 48;                  // Convert ascii to pin number
      switchPin();                        // Toggle state of that pin
    }
 
    if ( inChar == 49 ) { // 49 is 1, all LEDS on
      digitalWrite(2,HIGH);
      digitalWrite(3,HIGH);
      digitalWrite(4,HIGH);
      digitalWrite(5,HIGH);
      digitalWrite(6,HIGH);
      digitalWrite(7,HIGH);
      digitalWrite(8,HIGH);
      digitalWrite(9,HIGH);
    }
 
    if ( inChar == 48 ) { // 113 is 0, all LEDS off
      digitalWrite(2,LOW);
      digitalWrite(3,LOW);
      digitalWrite(4,LOW);
      digitalWrite(5,LOW);
      digitalWrite(6,LOW);
      digitalWrite(7,LOW);
      digitalWrite(8,LOW);
      digitalWrite(9,LOW);
    }
 
    if ( inChar == 114 ) { // 114 is r, all red LEDs on, all green off
      digitalWrite(2,HIGH);
      digitalWrite(3,LOW);
      digitalWrite(4,HIGH);
      digitalWrite(5,LOW);
      digitalWrite(6,HIGH);
      digitalWrite(7,LOW);
      digitalWrite(8,HIGH);
      digitalWrite(9,LOW);
    }
 
    if ( inChar == 103 ) { // 103 is g, all green LEDs on, all red off
      digitalWrite(2,LOW);
      digitalWrite(3,HIGH);
      digitalWrite(4,LOW);
      digitalWrite(5,HIGH);
      digitalWrite(6,LOW);
      digitalWrite(7,HIGH);
      digitalWrite(8,LOW);
      digitalWrite(9,HIGH);
    }
 
  }
}
 
// my own function to toggle state on a pin
void switchPin() {
  val = digitalRead(pin);
 
  if ( val == LOW ) {
    digitalWrite(pin,HIGH);
  } else {
    digitalWrite(pin,LOW);
  }
}
 

Then to connect your computer to the device, first connect the serial cable and then use a terminal client such as screen to make the connection.

screen /dev/ttyACM0 9600

 

See the screen man page for more options.

If you have problems connecting, make sure your user is in the `dialout` group.

 

The source code and source for the diagram are available on github.


iam - Not getting distracted

Posted by richard on January 22, 2013

There has been a lot of discussion recently about the amount of time that is wasted in each day from recovering from interruptions whilst programming.

Ninlabs research has written an excellent post called Programmer Interrupted and Swizec Teller has written a book on the subject and an interested article on why programmers work at night.

Something a lot of people do when getting interrupted is to make a note somewhere in a file or even the code they are working on, as a prompt to come back to. I have a similar approach but as I work mainly on the command line I have a simple bash script called "iam" to make this a trivial thing for me to do.

If I need to make a reminder, i simply do:

     $ iam writing a blog post about iam

And when the distraction has passed, if I find myself wondering "I have forgotten what I was doing now", I run the command again

    $ iam
    At 21:07 on 22/01/2013 I was writing a blog post about iam

 

If you want the script, iam is on github and there are some more examples in the README file.


Interface injection in ZF2

Posted by richard on January 21, 2013

Getting dependencies into services and models using Zend\ServiceManager can be done in a few ways. Using factories for example provides a simple way to inject a service into a controller, or some configuration into a service.

But this can become tedious and repetitive when injecting something like database connection settings or a configured ORM instance into models for 300 database tables. You would end up with a factory for each model and each factory would be almost identical. This amount of duplication clearly cannot be right.

Using interface injection can help in situations like this and is very simple to set up.

Let's assume we want to inject a configured instance of RedbeanPHP into each model. The configured instance is referred to in the service locator as Redbean\RedbeanService.

First we create an interface

    <?php
    // module/Application/src/Application/Model/RedbeanAwareInterface.php
 
    namespace Application\Model;
 
    use Redbean\RedbeanService;
 
    /**
     * RedbeanAwareInterface
     *
     * Implement to inject Redbean into models
     */ 
    interface RedbeanAwareInterface
    {
        /**
         * Assign the Redbean service to the model
         *
         * @param RedbeanService $redbean
         * @return void
         */
        public function setRedbean(RedbeanService $redbean);
    }

 

Then in the configuration you add an 'initializers' section to the 'services'

   // config/module.config.php
 
   // .. existing code ...
   'service' => array( 
        // ... existing code ...
        'initializers' => array(
            'RedbeanAwareInterface' => function($model, $serviceLocator) {
                if($model instanceof RedbeanAwareInterface) {
                    $redbean = $serviceLocator->get('Redbean\RedbeanService');
                    $model->setRedbean($redbean);
                }
            }
        ),
    ),
 
    // ... existing code ...

 

Then in the Models you can use this interface to get RedbeanService injected by the service manager by simply implementing the interface.

    <?php
    // module/Application/src/Application/Model/ExampleModel.php
 
    namespace Application\Model
 
    use Redbean\RedbeanService;
 
    class ExampleModel implements RedbeanAwareInterface
    {
        /**
         * @var Redbean $redbean
         */
 
        /**
         * setRedbean
         *
         * Assign Redbean
         *
         * @param RedbeanService $redbean
         * @return void
         */
        public function setRedbean(RedbeanService $redbean) 
        {
             $this->redbean = $redbean;
        }
 
        // rest of class ...
    }
 

 

Then whenever you use the ExampleModel, the service manager sees that it is an instance of RedbeanAwareInterface and injects RedbeanService into the model.


Hello World in ZF2

Posted by richard on January 14, 2013

It appears to be a common complaint that Zend Framework 2 is simply too complicated and that the getting started guide requires that you know tools like Git, Composer, how to set up a virtual host, PHPUnit, poedit and so on.

It is a difficult situation to resolve because on one hand the getting started tutorial needs to be just that, a guide to get you set up and working. On the other hand there is benefit in using the tools and practices that as a PHP developer you probably should know.

I see people complain that they want to learn Zend Framework and being expected to learn composer first is in some way a step too far. To be honest, if you are a developer unwilling to learn something like Composer then ZF2 is probably not going to be a good fit with how you currently work. ZF2 is all about building reusable modules and in order for this to work, you need to be working in a way consistent to how ZF2 and many other projects work. Part of that requires using the same tools as those projects and Git and Composer are two such tools.

The getting started tutorial is based on the ZendSkeletonApplication, which is a reasonable starting point. I personally find that I remove a lot of bits, such as translations and default routes before starting with the ZendSkeletonApplication, so I suspect this skeleton could be cut a little closer to the bone.

I thought perhaps writing a no fuss Hello World! application on ZF2 would be a useful alternative to the ZendSkeletonApplication for getting started. So I have written one called RjhHelloWorld and it is downloadable as a ZIP file from Github. You do not need to use Git or Composer and ZF2 is already provided in the Zip file.

You just extract the zip file somewhere and configure a virtual host to point to the public/ directory.

What I discovered in doing this, is that it provides a small codebase which runs quickly and is easy to understand, however it is not apparent how to build anything larger based on this simple application. Hopefully though it will serve as a springboard to get you started.

 


RjhRedbean is now listed on modules.zendframework.com

Posted by richard on November 2, 2012

There has been a pull request in for some time to get RjhRedbean accepted as a ZF2 module and added to modules.zendframework.com. This week that site has had a complete overhaul and it is now possible to get modules added.

I am pleased to say that RjhRedbean is now listed on modules.zendframework.com.

 

Please check it out and if you have any comments or suggestions or find any problems, please let me know.


How to use FUSE models in RjhRedbean

Posted by richard on October 26, 2012

With special thanks to Marc Fonteijn for providing feedback, advice and ideas.

 

For an explanation of what FUSE models are, you will need to read the Redbean Documentation.

The problem with getting this to work in RjhRedbean is that because ZF2 is using namespaces, that breaks the way FUSE works in getting every bean to find its model automatically.

To fix this we need to :

 1. Make sure that the model is not in a named namespace
 2. Ensure the class can be found by ZF2

Using the example given in the Redbean Documentation, we want to create a model for the `band` bean to ensure that we do not have more than 4 members in a band. This example assumes you are working in the Application module.

By convention in ZF2, you put your source files under modules/Application/src/<namespace>/, so files in the Application\Controller namespace are in modules/Application/src/Application/Controller/. In this case where we want the class "Model_Band" to be in the global namespace, the file will be modules/Application/src/Model_Band.php.

Create the file with the following content:

<?php
 
class Model_Band extends RedBean_SimpleModel 
{
  public function update() 
  {
    if (count($this->ownBandmember) > 4) {
      throw new Exception('too many!');
    }
  }
}

 

So we now have a FUSE model in the global namespace called Model_Band. FUSE will use this class name when attempting operations on any beans called `band`.

We now need to tell ZF2 how to find this class. We do this using a class map, which you need to edit manually.

First edit module/Application/Module.php so that the autoloader will load a classmap file. The file should look like this :

<?php
 
namespace Application;
 
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
 
class Module
{
  public function onBootstrap(MvcEvent $e)
  {
    $e->getApplication()->getServiceManager()->get('translator');
    $eventManager = $e->getApplication()->getEventManager();
    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);
  }
 
  public function getConfig()
  {
    return include __DIR__ . '/config/module.config.php';
  }
 
  public function getAutoloaderConfig()
  {
    return array(
      'Zend\Loader\ClassMapAutoloader' => array(
        include __DIR__ . '/autoload_classmap.php',
      ),
      'Zend\Loader\StandardAutoloader' => array(
        'namespaces' => array(
          __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
        ),
      ),
    );
  }
}

 

Finally, we create the classmap to be used by the autoloader containing our new Model_Band class. Edit module/Application/autoload_classmap.php so it look like:

<?php
 
return array(
  'Model_Band' => __DIR__ . '/src/Model_Band.php',
);

 

That should just work. When you try to add a more than 4 members to a bean called "band", the Exception will be thrown.


RjhRedbean is now available on Packagist

Posted by richard on October 16, 2012

 

When I wrote RjhRedbean, I thought it would be useful to make it easier for me to get RedBeanPHP ORM set up in my own projects. I never expected anyone else to use it.

Recently though, I have received emails and found questions on stackoverflow and people are using it in their Zend Framework 2 projects too. I am happy to see it is providing some value to others but it has also raised questions relating to installation and configuration.

So I wrote up some installation notes, and explained how to add my github repository to your composer sources. Although this is a minor thing to have to do, I felt that I was making things harder than they needed to be.

So I have setup RjhRedbean on Packagist and you can now easily add RjhRedbean to an existing ZF2 application by editing your composer.json file and running a composer install. To install RjhRedbean into the ZF2 Skeleton Application, would require the following composer.json file:

{
    "name": "zendframework/skeleton-application",
    "description": "Skeleton Application for ZF2",
    "license": "BSD-3-Clause",
    "keywords": [
        "framework",
        "zf2"
    ],
    "homepage": "http://framework.zend.com/",
    "require": {
        "php": ">=5.3.3",
        "zendframework/zendframework": "2.*",
        "gabordemooij/redbean": "dev-master",
        "richardjh/rjhredbean": "dev-master"
    }
}

 

You can find out more on the Github project README file and if you find any problems or think things can be explained better, please let me know.


Class 'SphinxClient' not found

Posted by richard on October 10, 2012

SphinxClient is available as a PHP extension from pecl.

To get this installed on Ubuntu 12.10 you need to first install pear

sudo apt-get install php-pear

Then install php5 and libsphinx client development packages

sudo apt-get install php5-dev libsphinxclient-dev libsphinx-client-0.0.1

Then you should be able to install SphinxClient using pecl

sudo pecl install sphinx

You now need to enable this in apache2. So edit /etc/php5/apache2/php.ini and under Dynamic Extensions, add extension=sphinx.so, so it looks like

;;;;;;;;;;;;;;;;;;;;;;;;
; Dynamic Extensions ;
;;;;;;;;;;;;;;;;;;;;;;;;
extension=sphinx.so

 

Then finally restart apache2

sudo service apache2 restart

 

 


Tags