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!

Wisconsin Delight

Five things I think are currently awesome.

Microsoft Surface Pro 4.  It is the most generally useful computer I’ve ever owned.  Particularly if you are interested in making graphical works. For years and years I’ve dreamed of having a computer that I can draw on, and the Surface Pro is that machine.  I’ve been having tons of fun making stuff with the Surface Pro and Corel Painter.  Sure, you can get a Wacom Cintiq, but that’s like two grand.  The Surface Pro 4 I got was under a thousand.

Doctor Strange.  This was the Marvel movie that was expressly made for me.  Everything about it was great.  To the degree I hated the Thor movies, I love Doctor Strange.  Not to mention it has one of the two best Pink Floyd references in the Marvel Comic Universe.  Which brings us to ….

Legion.  The new Marvel show on FX has just a fantastically surreal quality to it that really separates it from most other shows on television right now. And it has another Pink Floyd reference.  The main character’s girlfriend’s name is Syd Barrett.  Speaking of television shows, if you haven’t already, you should check out …

The Expanse.  Finally, a little science in the science fiction.

Wisconsin Delight.  You know how in that story The Lion, the Witch and the Wardrobe, the frozen queen tempts the little kid with Turkish Delight?  Turns out Turkish Delight actually kind of sucks in the real world.  But also, after a jaunt through Wisconsin, I came home loaded up with cheeses, sausages and sex olives, and so internally, I have started to think of the foodstuffs commonly referred to as charcuterie, instead as Wisconsin Delight.  And it’s freaking deliciousness.  I could live on a diet of Wisconsin Delight.

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.

So if you’re looking for a meal that you can cook at home, which isn’t too hard in terms of technique or ingredients, but which will strike your friends as fancy as heck, let me suggest you consider doing a menu that’s based around a duck.

Duck is one of those proteins that most folks never get around to experimenting with at home, so it has a kind of implication of the exotic.  It’s also fairly easy to work with (assuming, of course, you’re not uncomfortable working with a whole bird).  Additionally, you’ve got the added benefit that when you cook a duck, you get as a by-product a whole bunch of beautiful, golden duck fat, which you can use for a variety of other stuff for the next month or two.  If you buy rendered duck fat on it’s own, it’s a fairly expensive proposition.  Amazon has it for $15 a bottle, for instance.  That’s the cost of an entire frozen duck.

I like to prepare my duck two ways — I sauté the breasts in a pan, and I do the rest of the meat as a kind of mock confit.

An arugala salad with duck skin cracklings and a duck fat vinegarette

An arugala salad with duck skin cracklings and a duck fat vinegarette

You break down the duck, and strip off all the skin and fat that’s left on the carcass (leave some of the skin and fat on the legs, thighs, and wings).  Cut all the skin and fat in to small morsels, then render them in a low pan for about 30 minutes or so.  All the little bits get brown and crunchy, and all the fat melts out.  Strain it out, keep the fat, and the crackly brown bits are yours to use as you like.  I like to add them to the salad, for instance.  They’re like little chicharrones. Pro-tip — use some of that duck fat when you make the salad dressing, too.  Just sub it in instead of olive oil.

Take the duck breasts and set them aside.  The rest of the duck pieces go into a baking dish, skin side up.  Salt and pepper them generously, add a little thyme or whatever herbs you like.  Pour the reserved duck fat over the meat; you should have enough to nearly cover it, but not quite.  Then stick that bad boy in the oven at about 300 degrees for about two, maybe two and a half hours.

That long, slow heat draws even more of the duck fat out, and the skin crisps up slowly.  The meat itself takes on this velvety, luscious quality from practically poaching in the fat.

Then, before you serve, slash the layer of fat on the duck breasts in several places, and sauté the duck breasts skin side down in a medium pan.  Flip them once, after the skin has gotten a deep brown.  Shoot for cooking them a little less than you think they need; if they’re medium, they’re perfect.

Slice the breast, serve it with some of the confit, and boom, duck two ways.  Make a little pan sauce if you like to serve with the breast meat.

Here’s how it looked when I served it with some fresh asparagus and turnips from the farmer’s market:

11709522_10155842197410691_3588947329586360789_n

Not to mention, you’ve probably still got some duck bones and carcass left. Throw that in the stock pot, make up a slow-cooked batch of duck stock, and then freeze that shit. Next time you’re making a soup or a sauce or a risotto or something, reach for the duck stock and push the awesomeness to the next level.

If it’s value you’re interested in, you can hardly beat duck. One bird goes a long way in terms of ingredients.  By the time you’ve used up everything you’ve made, you’ll have cooked at least four or five high-quality dishes, and probably more than that.

Tales from my neighborhood.

Two men died after bullets intended for the rapper hit them. The killers didn’t miss the third time.

Click here for the full article

Posted from Facebook

Back in 1984, in Rogers Park, Chicago, there existed (and still exists today) a Jewish preschool on Touhy Avenue, the street where I currently live.

It happened that a woman was picking her four-year-old daughter from school, and as they were walking through the hall, a janitor tried to tickle the little girl, and the girl told him to leave her alone.

So the mom asks the girl about it later, and the girl alleged that the janitor had previously tickled her private parts.   The allegations were reported to the police, who then interviewed something like 80 kids at the school.  Some of the kids apparently reported that there were satanic rituals going on at the school.  Some kids claimed they had seen the teachers there kill a baby, cook it in a kettle, and then eat it.

Ultimately, there was an investigation, the janitor was charged with molestation and the school closed down for a while.  Eventually, the janitor was acquitted, and two-hundred-something charges against the school and various teachers were dropped, because of either lack of evidence or a bumbled investigation, depending on who you ask.

In case you were wondering because of the superficial similarities, A Nightmare on Elm Street was also released in 1984.

I discovered this today because we published an article about a couple in Texas who just had their 20-year-old convictions tossed in a similar satanic ritual abuse situation.

And that led me to an article one of my co-workers wrote back in 1987 about the Rogers Park case.

Here’s the most authoritative version I’ve been able to find in my brief research.  It appears from this that the judge in the case felt like there was a real possibility that sexual abuse had occurred, but because it had become this satanic cult witch hunt, the investigation had been compromised, and thus there was reasonable doubt, requiring the acquittal.

Interesting story, eh?

So, I honestly can’t believe it took me so long to figure this trick out.

If you’re like me, you’ve made hamburgers or cheeseburgers at home plenty of times.  And, if you’re like me, you’ve learned to unplug the battery from the smoke detector before you start cooking the patties because it’s going to undoubtedly smoke up the house a little.  There’s even an episode of Julia and Jacques Cooking at Home in which Julia Child jokes that the best place to cook hamburgers is at your friend’s house, because it’s inevitably going to smoke the place up.

I mean, you want to get a good sear on those things, and since it’s ground meat, you definitely want to get it cooked well.  Beef fat’s got a low smoke point, though, so by the time the patty is cooked, the beef fat has started to burn, and you end up smoking everything up.

But it turns out the secret is simple.  For years and years, I’ve just thrown the patties into a dry pan because I knew they’d render plenty of fat when they cook, and I didn’t see any reason to add more fat.  But the secret is to use a little bit of oil with a high smoke point to get the patties started.  Just pour in maybe two or three teaspoons of something like canola oil into the pan (I prefer cast iron) before you put the burgers in, and that will raise the smoke point of the beef fat which renders as the patty cooks.

Simple and brilliant, and makes it much more convenient to cook hamburgers at home in a small apartment kitchen.

“Just how charitable are you supposed to be when criticizing the views of an opponent?”

Click here for the full article

Posted from Facebook

 I’m about 400 pages deep into a book about rationality and improving your cognitive functionality, so I figured, what the heck, let’s look at what contemporary christians think are their most convincing arguments. Also, I was out of horror movies to watch, and I had a few drinks in me.

So the story is essentially thus: A kid is a freshman in college, and signs up for an introductory undergrad philosophy class. The teacher of said class, as he is passing out his syllabus, says that everyone has to sign a piece of paper saying that “God’s Dead”, or else suffer dire consequences. Everyone signs except for our hero, who is then told he has to convince his class of 40 or so kids that god exists, or else he fails (or, as the movie repeatedly insists upon, “commits academic suicide”). Add in a few insipid side stories, and you can imagine how plot goes from there.

I was extremely disappointed in this movie, I have to say. I mean, it’s just a jumble of weird christian fantasies about what they imagine atheists must be like. The epistemology is not just flawed, it’s more like a melange of lousy justifications for a foregone conclusion — oh, gosh, doesn’t the Big Bang theory sound just like the account of creation in Genesis? No? Well, here’s an appeal to authority. Not buying that? Maybe you’d prefer to believe that atheists are all just secretly angry with God. Etc.  It’s like a 90-minute live-action Chick tract.

Every character a caricature. Every plotline a melodrama. And the whole thing ends with all the newly-saved freshmen attending a christian rock concert en masse, where they all text everyone in their phonebooks with the message “God’s Not Dead”. As the credits roll, the audience of the film is encouraged to do the same. Because, you know, get on the bandwagon.  From beginning to end, it’s a cavalcade of bad logic, fallacious reasoning, wishful thinking and offensive stereotypes of all kinds.

But ultimately, it comes down to this: I’ve been in my fair share of undergrad philosophy courses. I’m fairly confident that nobody involved in the making of this movie can say the same thing. Philosophy professors are really, really lousy villains in real life.

“God’s Not Dead” on IMDB.com