Backend ORM - PHP ORM MySQL class for the masses!

I finally did it, I released my ORM class(es) to the public.

What to expect:

  • Retrieving data is much faster
  • Inserting and updating data is much much faster
  • Handles the everyday MySQL querying
  • Creates explicit SQL that stops laziness like SELECT * FROM...
  • It doesn't do everything, this was built to remove the everyday SQL man handling that gets done everyday. I would imagine it would cover 90-95% of your current queries

Try it out now:

https://github.com/drewbroadley/Backend-ORM

 

Example usage:

<?php
include_once("Backend/Backend.class.php");
include_once("Backend/Backend_ORM.class.php");

define(DB_HOST, "localhost");
define(DB_NAME, 'db_name');
define(DB_USER, 'username');
define(DB_PASS, 'password');

// Initiate connection
$backend = new Backend(DB_HOST, DB_NAME, DB_USER, DB_PASS);

// Retreive All Users
$users = new Backend_ORM('users');
$users->get();
while ($user = $users->next())
{
    // Field
    print $user->name;
    
    // As Array
    print_r($user->get());
}

           
// Retreive Example User
$user = new Backend_ORM('users');
$user->get(1);
print $user->name;


// Create User
$user = new Backend_ORM('users');
$user->name = "Test User";
$user_id = $user->save();

// Update User
$user = new Backend_ORM('users');
$user->get(1);
$user->name = "Updated Test User";
$user->save();



// OTHER FEATURES

// Conditions (can be multiple
$user = new Backend_ORM('users');
$user->cond("name", "Test User");
// or
$user->cond("user_id > 10");

// Ordering
$user = new Backend_ORM('users');
$user->order("name", "asc");

// Limit
$user = new Backend_ORM('users');
$user->limit(10);

// Join Table
$user = new Backend_ORM('users');
$user->join('user_details'); // joins by default on PK
$user->get(1);
print $user->age;


// Cache query
$user = new Backend_ORM('users');
/* Insert complex query param's */
$user->get(null, 360); // Cache for 5 minutes

?>

Posted

PHP class variables as an array

A small "winner" function I use often, I love Reflection in PHP. It's an undocumented mystery that you gain a lot of power and flexilbity when you understand its use(s).

function as_array($class_name = null)
    {
        $class_name = ($class_name) ? $class_name : __CLASS__;

        $user = new ReflectionClass($class_name);

        $prop = $user->getProperties();
        $return = array();

        if ( ! empty($prop) )
        {
              foreach ( $prop as $var )
              {
                    if ( $var->isStatic() )
                    {
                        $return[(string)$var->getName()] = $var->getValue();
                    }
              }

        }

        return $return;

    }

Posted

Filecache - A mirrored Memcache class using files

A little class I created when I needed to develop in an environment where the live setup had Memcache, but the local environment didn't (and couldn't). I hope this makes someone happy someday :)

class Filecache
    {
        function addServer() { }

        function checksum($key)
        {
            return sprintf("%X", crc32($key));
        }

        function checksum_file($key)
        {
            return "/tmp/filecache_" . Filecache::checksum($key);
        }

        function get($key, $expire = false)
        {
            if (file_exists(Filecache::checksum_file($key)))
            {
                if (
                    (!$expire || (time() - filemtime(Filecache::checksum_file($key)) < $expire))
                )
                {
                    $code = file_get_contents(Filecache::checksum_file($key));                }
                else
                {
                    unlink(Filecache::checksum_file($key));                    $code = null;
                }
            }
            else
            {
                $code = null;
            }

            return json_decode($code);
        }

        function set($key, $value)
        {
            file_put_contents(Filecache::checksum_file($key), json_encode($value));
            return $value;
        }

        function flush() { `rm -rf /tmp/filecache_*`; }

    }

 

Posted

Wordpress, I hate it but I use it.

There are two things I do with every new Wordpress install, and they both exist in the wp-config.php file.

What you're going to achieve via this is per host settings for different environments (dev, test, staging, live...) and never have Wordpress force the hostname stored in the wp_config table.

First, remove the DB settings lines and put them into a new file wp-config-localhost.php. These will be used later.

Now add this set of lines into your wp-config below the WP_DEBUG line:

// Checking to see if host-specific config exists
$host_config_file = (ABSPATH . 'wp-config-' . preg_replace("/[^a-z0-9\-\.]+/","", $_SERVER['HTTP_HOST']) . '.php');
if (file_exists($host_config_file))
{
require_once($host_config_file);
}

This will search for a wp-config.php file corresponding to the hostname you request the Wordpress site through, i.e. http://www.mywordpresssite.com will transfer to wp-config-www.mywordpresssite.com.php. This allows you to set DB and other settings per host. Note: you cannot redefine constants, so you may want to pull anything you want to change into these hostname specific config files.

And directly under what you've just put in, put these two lines:

define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST'] . '/');
define('WP_HOME', 'http://' . $_SERVER['HTTP_HOST'] . '');

This will tell Wordpress to use the hostname of your site as the Wordpress home and site base url. This stops you installing it on a machine that had the Wordpress site accessed through http://localhost/ no longer try and throw the other person who is working on the site to http://localhost/, when they may have the site setup to be viewable through http://wordpress.mydomain.com/ etc.

I hope this helps someone, somewhere, out there, over the rainbow....

Posted

Wellington people - do you want some free in-house help with your misbehaving dog ?

  • Wont come, but you've been through obedience ?
  • Gets possessive over things, and growls when you try to take them away ?
  • Scared you'll get your hand bitten off if you try to take their dog bowl away ?
  • Barks/shows teeth at strangers ?
  • Aggressive towards other dogs ?

Or any other behaviour you really don't think your dog should be doing, I'm keen to help Hey all, I've been around dogs all my life, I've often found a bond with almost all dogs that I've met and my love for dogs has caused me to really want to understand them.

I've been studying dog behaviour/psychology for over a year, and am by nature a self-taught person. I've read most books on the subject and have taken a point of view of different approaches and it's really a dog-by-dog assessment on what's the best approach.
I took on a very special case SPCA dog (Border Collie mix called Sassy) who has some very severe trust/anxiety issues and am progressing very well with her.

  • What I'm keen on now, is to give myself eth other dogs that are not through family contacts.
  • Here's a summary of what I'll offer (usually will take 30min-1hr):
  • I will not hurt your dog, I will use little to no physical contact.
  • I can offer clicker training, but prefer an alternative method. It just depends how well you can control the emotion in your voice so we'll take it as it comes.
  • I will not offer help on person-aggressive and attacking dog cases, sorry (ask me in a few years). This is beyond my experience.
  • I will provide education to the owner(s) and a summary of the assessment in an email/pdf afterwards for you to take away and work with.
  • I am especially keen on working with post-adoption SPCA dogs.

Your dogs confidence is paramount, if your dog is feeling uneasy, I will not push them. I don't work with suppression or flooding techniques, I work by modification of behavior.

If you're interested, please email drew@broadley.org.nz or reply here with the following details:

Dogs Name:
Dogs Breed:
Dogs Age:
Where you got the dog:
If you're not the original owner, how long have you owned it:
Describe the problem:

I'd appreciate it if you could pass this onto people who it may come to help.

Posted

Marketing Idea #13 - Woof woof

Sick of those damn dogs barking throughout the day/night ? Ready to complain to the council, but knowing that it's going to take a fair bit of action before the owner really takes hold of how annoying their precious pooch is ?

A great community marketing scheme, due to people adopting a four legged friend and being ignorant to its needs, it causes a build up of frustration and stress which causes side effects of barking, tearing up the back yard and chewing to relieve this.

Currently when you complain to the council, they take the complaint and file it with a friendly "Thanks for getting in touch" reply. Second complaint gets a bit more action and a letter sent to the offending owner. Third complaint usually ends up in similar grounds of the result from the second complaint.
Nothing is being achieved, the owner isn't paying attention and most likely laughing at the letters. Here's where a better approach of the problem comes in. Education, and reasonable consequences...

Setup a council funded dog walking/dog care scheme, with a one/two representatives per region with animal behavioral training and dog obedience knowledge.
When a complaint comes in to the council they handle it as they normally do with one exception, the representatives do a quick check on the property. This allows them to assess the frustration and stress of the dog. What this achieves is two things:

1. Assesses the dog is not maltreated in anyway (within reason)
2. Confirms the problem at the indicated time(s)

Council records situation, and writes a reply letter to the owners property sharing the findings of the animal, and confirming if they also identified the problem and suggestions to educate the owner on why their dog may be causing disruptions. This gives a mediation type approach. A letter also goes out to the complainant stating what has happened, and what allocated duration they have before following up the complaint and any suggested non-confrontational methods they could use to communicate with the property owner.
Second complaint comes after the conditions haven't been met, and the owner is contacted stating their dog is still behaving in a manner as per the first complaint. They are notified that they will be visited in the evening of their choice so the council can initiate a dog walking service initially sponsored by the council to reduce the frustration of their dog and see if this improves the dogs behavior. Additional education is supplied to the owner on the system and introduction to the dog to the representatives who will be walking their dog.

The dog will go on a trial for two weeks, seeing if there is any immediate improvement. If there is improvement, then the council will supply the owner with enough education to complete their knowledge of animal behavior and why walking their dog is important. If there is no improvement, then owners are referred to a dog behavioral specialist.

If a third complaint arrives, then the council sends out a fine for the dog and the dog walkers come in and carry on their service until the fine value is reached. After each duration of dog walking has been completed, the council will reassess the situation with the owner.

This can also be offered as a subsidised dog walking service by the community council to reduce dog nuisance complaints to people who don't have time to walk their dog.

The dog walking service may not be feasible, but education and communication with the dog owners is a must.

Potential Clients:
Dog owners

Potential Mediums:
Interactive, Website, Print

Filed under  //  365marketingideas  
Posted

Ugh, so busy

The lack of updates reflect it, but I'll be back on top of the Marketing ideas this week....

Posted

Marketing Idea #12 - Cops and Robbers

Imagine you're racing around the tarmac, tires squealing, a cop on your tail with lights blazing. Is this a video game ? No. Sounds a bit too cliche ? Sure! But this is the appeal...

Put yourself up against the best on the NZ Police force. Setup on an open race track where you can backtrack on sections of the race track and the goal of the cop is to perform a pit maneuver and spin you 180 degrees to win. Identical cars are setup with bumper sections on the front/back to reduce damage and absorb impact. Cops have cars in the NZ Police force branding, and the "robbers" have cars in Dukes of Hazard or similar stereo-type paint jobs.

This can be used as training for NZ Police in the public eye to demonstrate how safe their apprehension methods are, and lets every person who has the want to see how good they are up against the people in blue. National qualifying events that boil down to a final at a defined race track.

This can become a community fundraising event and a great spectator sport annual event, with sponsorship from a car manufacturer. Potential to become a short life-span TV show or a recruitment drive styled event.

Potential Clients:
NZ Police, Defensive Driver Education (AA), Driver Training Companies (Holden, BMW, etc.)

Potential Mediums:
Interactive

Filed under  //  365marketingideas  
Posted