Ok, so this particular problem took me a while to solve, but it turns out to be a useful technique, at least in my case, so I’m reproducing it here in the hopes that if you’re searching around on the internet looking for an answer, it’ll save you a little bit of time.

First, let’s describe the problem.

Let’s say you have a basic Laravel class something like:

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;

class Aspect extends Model{
    public function display(){ ... }
}

And you have a bunch of other classes that extend your base class, including, possibly, classes that do not yet exist.

class SpecialAspect extends Aspect{
    public function display() { .... but with something different! }
}

class StupidAspect extends Aspect {
    public function display() {  ... and something else is different! }
}

Now, all of these classes will share the same underlying table, which includes a field which specifies what type of Aspect each record represents.

And what you want to do is to continue using Eloquent ORM to work with collections of aspects, such that belongsToMany() and the like will give you back a Collection object containing a bunch of Aspects, all cast into the correct sub-classes (e.g., [Aspect, Aspect, SpecialAspect, Aspect, StupidAspect]).

So you try it out, and you find everything is getting returned as the base class [Aspect, Aspect, Aspect, Aspect, Aspect].

Laravel thinks that you only want instances of the base class, but you don’t; you want the object with overridden methods to load correctly so you can work with them normally.

This is the classic use-case for the Factory pattern.

So how do you do it?

What you do is create a Custom Collection object to override the normal Collection method that your object uses.  In the Custom Collection, you iterate through the objects available, figure out what type the are supposed to be, and then create new objects of those types.  Then you essentially load the data into them manually, build them into an array, and replace the $items in the Custom Collection with your new array of objects.

So first, modify your base class to implement a custom collection method.  While you’re at it, make a manual_load() method as well; remember, the newCollection method is going to override the normal Collection method all the time, so if you don’t load your objects up manually, you’re going to get yourself into a situation with an infinite loop, until you run out of memory:

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;

class Aspect extends Model{

    public function display(){ ... }
    
    public function newCollection(array $models = []){
        return new AspectCollection($models);
    }
    
    public function manual_load(){
        // use the DB::select method to pull your data out of the underlying table
        // and add it to the respective properties on $this
    }

}

So far, so good.

Now, you’re going to want to build your custom Collection object:

class AspectCollection extends \Illuminate\Database\Eloquent\Collection {
    public function __construct($items){
        parent::__construct($items);
        $this->recastAll();
    }

    private function recastAll(){
        $new_collection_array = array();
        foreach ($this->items as $m){
            $new_object = AspectFactory::make($m->id);
            $new_collection_array[] = $new_object;
        }
        $this->items = $new_collection_array;
    }
}

You’ll notice from that class, there is yet a third class that we’re going to need, an AspectFactory class that decides what kind of object you’re going to create for each individual element, so we’ll create that too:

class AspectFactory{
    public static function make($aspect_id){

        $new_classname = 'App\DefaultAspect'; // <--- if we don't have a custom type, we'll use this as our default.

        $new_type_name = DB::select('SELECT aspect_name FROM { ... whatever query will give you the name you need} ); 
        $mutated_aspect_type = $new_type_name[0]->aspect_name;
        $custom_classname = 'App\\' . $mutated_aspect_type . 'Aspect'; // This string is the name of the class we're going to test for.

        if ( class_exists( $custom_classname ) ){
            // The custom class exists, so override our default.
            $new_classname = $custom_classname;
        }

        $finder = new $new_classname();  // Here, we create the new class.
        $finder->id = $aspect_id;        // Assign the ID to the new object
        $finder->manual_load();          // Call that manual_load() method we wrote for our base class.
        return $finder;                  // Send our custom class back to our Custom Collection.    
    }
}

So now, if you have a relationship that looks like:

App\Subject->belongsToMany(‘App\Aspect’);

Then you can do Eloquent operations such as:

$s = new Subject::find(1);
foreach ($s->aspects as $a ){
     $a->display();
}

And the correctly overridden display() method will spit out whatever it is you’ve got it doing, because your Collection will look like:

[
   0 => Aspect, 
   1 => Aspect, 
   2  => SpecialAspect, 
   3  => Aspect, 
   4  => StupidAspect
]

Or whatever.

And there you have it.  Implementing the Factory pattern with Laravel (5.4).

 

 

 

Hey, so if you’re working with Drupal 7, particularly doing module development, you might find yourself find-and-replacing on the same kind of boilerplate code to set up a new module every time.

Well, I got sick of it, so I made a quick little generator for boilerplate code for Drupal 7 module development.  You can run it from the command line, and it’ll get you down to the interesting stuff in no time.

As an added bonus, I’ve included another command line script you can use to generate form arrays that are compatible with the Drupal 7 Form API.

Give it a looksee over at Github.

If you make anything interesting with it, let me know!

Do this: Right now, take out your smartphone (presuming you use one that runs iOS or Android.)  Go to your app store of choice (or just follow this link) and install an app called Signal.  It’s free.  It costs you nothing.  But one day, it may help you in ways you cannot yet foresee.

Signal is a privacy and security app that replaces your built-in SMS/text message software.  It seamlessly handles your text messages for you, just like you’re used to now.  But as an added bonus, it automatically encrypts texts that you send to other Signal users.  The software uses end-to-end encryption to ensure nobody can eavesdrop on your texts.  That includes the people who make the software, the NSA, the FBI, the phone company, your tricky hacker kids, the people sniffing your wi-fi at the Starbucks, and everyone else in the world.  It means you can rest assured your private communications STAY PRIVATE.

In addition to encrypted texts, you can also use Signal to make encrypted phone calls, video calls, and picture messages.  It’s open-source, so it’s been peer-reviewed by the cybersecurity community.  It’s dead simple; easy enough that anyone can use it effectively.  And did I mention that it’s free?

Look, it’s 2017.  Donald Trump is going to be inaugurated as President of the United States on Friday, at which point, the controls of the most sophisticated surveillance apparatus in the entirety of human history will be at the disposal of a thin-skinned, sociopathic demagogue.  18 months from now, you don’t want to find yourself in a situation where you you’re asking, “Why didn’t I think of encrypting my communications sooner?”  And even if you’re a straight shooter who never does a single thing wrong, and never wants to privately express controversial opinions, you should still use Signal to secure your communications.  What if you are, or know, a journalist, an activist, or a protester who fears being targeted for retribution or censorship?  What if you need to pass sensitive financial information to your accountant, or your lawyer, or your family?  Are you going to PGP-encrypt your emails?  If you’re like most people the answer is no; PGP-encrypted emails still frustrate even sophisticated techies.  Don’t make it hard on yourself, when Signal is so easy to use.

Edward Snowden recommends using Signal, and he’s the kind of guy who has to worry about assassination attempts by state-level adversaries.  World-renowned security researcher Bruce Schneier recommends it.  The Electronic Frontier Foundation recommends it.  I recommend it.  It costs you nothing, and it could one day protect you from fraud, scams, and theft.  It may one day save your life or the life of someone you care about.  Go install it now.  Seriously.

Good stuff.

http://ift.tt/1EeNUW1

On a warm day in April 2013, I was sitting in a friend’s kitchen in Paris, trying to engineer serendipity. I was trying to get my…

Click here for the full article

Posted from Facebook

 In the January 9th New York Times Fashion & Style section, there was a charming article by Mandy Len Catron called “To Fall in Love With Anyone, Do This“.  In it, she talks about some research published back in 1997, in which professor of psychology Arthur Aron and his co-authors describe a method for inducing interpersonal closeness between strangers.

Catron writes:

I explained the study to my university acquaintance. A heterosexual man and woman enter the lab through separate doors. They sit face to face and answer a series of increasingly personal questions. Then they stare silently into each other’s eyes for four minutes. The most tantalizing detail: Six months later, two participants were married. They invited the entire lab to the ceremony.

“Let’s try it,” he said.

She and her partner googled up the questions and went through the procedure, which they apparently enjoyed a great deal:

You’re probably wondering if he and I fell in love. Well, we did. Although it’s hard to credit the study entirely (it may have happened anyway), the study did give us a way into a relationship that feels deliberate. We spent weeks in the intimate space we created that night, waiting to see what it could become.

Adorable, right?  Anyways, it struck me that other folks might want to try the experiment themselves, and it’d be helpful if the whole thing was all together in one place, accessible from a smartphone so that it would be easy to try with a date, for instance.

So I had a few extra hours over the last few evenings, and I threw together a little mobile-friendly, touch-friendly web app version of the experiment.

I took the 36 questions from the original study directly, along with a slightly modified version of the instructions, and I included a little timer that will count down four minutes for the eye contact exercise.  The whole thing is just HTML and Javascript, and weighs in at a little over 260 lines of code, all told.

You can try it yourself here:

http://www.ianmonroe.com/instantcloseness/

I’ve posted the code on Github, so feel free to fork it and make improvements if you feel so inclined.

The game is called “Damage Control”. Who wants to play?

David Sparshott Damage control is an excruciating, highly addictive game that among my friends has destroyed relationships, rekindled others, threatened to ruin careers, sparked sexual intrigue, and caused no end of terror and laughter. It is a game for two friends, and best played drunk. The instru…

Click here for the full article

Posted from Facebook

A novice asked the Master: “Here is a programmer that never designs, documents or tests his programs. Yet all who know him consider him one of the best programmers in the world. Why is this?”

The Master replied: “That programmer has mastered the Tao. He has gone beyond the need for design; he does not become angry when the system crashes, but accepts the universe without concern. He has gone beyond the need for documentation; he no longer cares if anyone else sees his code. He has gone beyond the need for testing; each of his programs are perfect within themselves, serene and elegant, their purpose self-evident. Truly, he has entered the mystery of Tao.”

Click here for the full article

Posted from Facebook

This is why I prefer to keep my passwords in an offline password manager, namely KeePassX.

I think this discussion came up once before, and Scott Schmitt asked me why I thought KeePass was better than LastPass — I didn’t have an example to point to at the time, but this is why. The fewer people that can even see my database file, let alone decrypt it, the better I feel about it.

Adoption of poorly secured password managers opens a single point of failure.

Click here for the full article

Posted from Facebook

Excellent web-based e-book discussing modelling cognition probabilistically and generatively.

With live code samples to mess around with to illustrate what they’re talking about.

Extremely interesting stuff, and not too dense. If you’re interested in making or learning about intelligent software, this should keep you busy for a little while.

In this book, we explore the probabilistic approach to cognitive science, which models learning and reasoning as inference in complex probabilistic models. In particular, we examine how a broad range of empirical phenomena in cognitive science (including intuitive physics, concept learning, causal r…

Click here for the full article

Posted from Facebook

Ok, listen, I’m not going to get into the details or whatever, but it was recently brought to my attention that I really, really should be backing up my MySQL databases on a daily basis at least.  So here’s the recipe.  Modify and use it for your own purposes, and don’t be as dumb as I am.

Create a directory to hold your backups.
Create the following shell script in your backup directory.  Substitute your own info for the stuff in brackets.

backup_script.sh:

#!/bin/sh
logfile=/[PATH-TO-BACKUPS]/backup_script.log
echo "------------" >> $logfile
echo "Starting MySQL Database backup script" >> $logfile
location=/[PATH-TO-BACKUPS]/backup_"$(date +'%d_%m_%Y_%H_%M_%S')".sql
mysqldump -u root --password='[YOUR-PASSWORD]' --opt [YOUR-DATABASE] > $location
echo "Completed MySQLDump." >> $logfile
gzip $location
echo "GZipped the backup file "$location >> $logfile
echo "Removing backups older than 10 days." >> $logfile
find /[PATH-TO-BACKUPS]/ -maxdepth 1 -type d -mtime +10 -exec rm -rf {} \;
echo "Old backups removed." >> $logfile
echo "Backup script completed on "$(date +'%d_%m_%Y_%H_%M_%S') >> $logfile
echo "------------" >> $logfile
exit 0

Set the permissions to 700, to make sure nobody can see your plaintext MySQL password.

Edit your cron tab to run the shell script once a day (or however often you think is prudent.)

To unzip the backed up SQL file:

gunzip -v [YOUR-BACKUP-FILE].gz

To restore your backed up SQL dump:

mysql [YOUR-DATABASE] < [YOUR-BACKUP-FILE].sql

Take it from me, kids. Only fools don’t back up their work.