How to Bind to Eloquent Model Event in Laravel 5

Whenever a Laravel model is modified there are a number of events that fire that allow you to trigger your own action(s). For example, in my PoliticsEQ application I needed to calculate some statistics about keywords and sentiment scores and store them in a separate table to improve performance for some of the front in graphs. The challenge was making sure the keyword statistics table was updated whenever a keyword was added or updated.

Laravel gives you the following events right out of the box: creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored. You can get the particulars here. Most of them are pretty intuitive.

In my case it made sense to use the “saved” event. To make this happen was remarkably. All I had to do was create a new “Service Provider” and use the Event::saved pattern in the provider’s boot method.

So first I created a KeywordStats provider.


namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Keyword, App\KeywordStat;
use Log;

class KeywordStats extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        Keyword::saved(function($keyword) {
          $stat = KeywordStat::where('keyword_name', $keyword->name)->first();
          if (!$stat) {
            $stat = new KeywordStat(['keyword_name'=>$keyword->name]);
          }
          $stat->sentiment_avg = Keyword::where('name', $keyword->name)->avg('sentiment_score');
          $stat->total_usages = Keyword::where('name',$keyword->name)->get()->count();
          $stat->save();
          Log::info("Updated {$keyword->name} / avg: {$stat->sentiment_avg} / count: {$stat->total_usages}");
        });
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        
    }
}

Then I simply registered the provider in the config/app.php providers array:


    App\Providers\KeywordStats::class,

Covert all tables from MyISAM to InnoDB

Here’s a quick one liner to convert all tables on in a specified database from MyISAM to InnoDB:

mysql -Bse "SELECT CONCAT('ALTER TABLE ',table_schema,'.',table_name,' engine=InnoDB;') FROM information_schema.tables WHERE engine = 'MyISAM' and table_schema = 'your_database_name';" | xargs -I {} mysql -e {}

Boom! You’re welcome.

Hide WordPress Post from All Queries

Problem: you want to create a variation of a page but you don’t want it to show up on the home page or in any archives or anything. You just need a direct link so you can share it with someone.

Solution:

add_action('pre_get_posts', 'hide_hidden_posts');
function hide_hidden_posts($query) {
  if ( is_admin() ) {
    return $query;
  }

  if ( is_single() AND $query->is_main_query() ) {
    return $query;
  }
  $ids = wp_cache_get('hidden_posts', 'posts');
  if ( !$ids ) {
    global $wpdb;
    $ids = $wpdb->get_col("SELECT post_id FROM {$wpdb->prefix}postmeta WHERE meta_key = 'hide_post'");
    wp_cache_set('hidden_posts', $ids, 'posts');
  }
  $query->set('post__not_in', $ids);
  return $query;
}

This function will modify all WordPress’ frontend queries to exclude any posts with a custom field “hide_post”, except in the case that the query is the main query on a single post page.

Caveat: This will only be functional for plugins and themes using the WP_Query api. Custom queries will not be modified.

High-Performance WordPress Basics

Getting started with high-performance WordPress requires understanding the concepts of speed, scale, and elasticity.

What do we mean by WordPress performance anyway?

You cannot separate the definition of “performance” from the overall purpose of the site itself.

If you’re a small business who just needs to post your store’s hours and contact info, a 1-second improvement in load-time may not be all that important to you — especially once you consider the additional cost. Everyone wants a faster more efficient site, but time is not an infinite resource and–unless you are Bill Gates or Warren Buffet–neither is money.

But if you are a search marketer, obsessing over page rank, bounce rates and conversions then 1 second can change your world and will probably be worth every penny you put into it.

As you read this book always keep recommendations in context of your overall purpose.

Dimensions of WordPress Performance

There are three primary consideration when talking about WordPress Performance:  speed, scale and elasticity. This ebook examines all three but will be mostly concerned with speed and scale. Elasticity comes mostly from the server/infrastructure and as such will only be dealt with in the hosting discussion.

Speed is an easily understood concept. How fast does my page load damnit! That’s all you need to know. It’s not quite this simple of course, but for the introductory chapter it’ll suffice.

Scale is a slightly more complicated concept. What do we mean when we ask can my application scale?

Computing power is a limited resource and the performance of your website or application will be impacted by the available and consumption of that resource.

An analogy.

Imagine a bagel shop owner in a small town. They get healthy foot traffic but not enough to afford an employee so they do everything themselves. They take the orders, make the bagels, ring the register. This can totally work so long as the number of people coming in and placing orders isn’t any more than can be served relatively quickly. But as more people come in, orders pile up, wait times increase, and the customer experience is wrecked.

What worked at the scale of one customer every five minutes broke down once there were two.

Of course our intrepid Bagel-ista will inevitably have to hire someone to help her out. But if she waits too long she’ll risk losing business because of the poor customer experience. She might just go ahead and hire early expecting the increasing demand. But what if business grows slower than expected? She’s spending more than she can afford on help she doesn’t need yet.

WordPress Scaling is a Balancing Act

The same goes for websites and application. You could spend thousands of dollars a month on sophisticated Amazon AWS machinations but not have a single customer to support the investment. Likewise you could go super-cheap with BlueHost or DreamHost and end up with a crashed server on the biggest day of your business.

It’s a balancing act. And there is no right equation or server or plugin that can make the decision for you. But you can plan ahead, accepting that those growing pains will happen and putting yourself in a position to scale as rapidly as possible when that time comes.

Strategies For WordPress Performance and Scale

Given the analogy above you can see to competing strategies developing, an aggressive or over-investment strategy and a conservative or under-investment strategies. Both have advantages and disadvantages and either can be used successfully.

Aggressive v. Conservative

The key consideration of the aggressive strategy is a complete intolerance downtime. In the movie “Social Network”, Mark Zuckerburg is memorably quoted saying:

Okay, let me tell you the difference between Facebook and everyone else, we don’t crash EVER! If those servers are down for even a day, our entire reputation is irreversibly destroyed! Users are fickle, Friendster has proved that.

This is a supremely aggressive strategy, but it was probably warranted given that the ONLY market advantage Facebook had was popularity.

I think too often though those with sites/applications very different from Facebook feel they need the same strategy.

Downtime is definitely a problem, especially when it happens at an inopportune time.The advantage to an aggressive strategy is that if done right, a promo video going viral will be no big deal. But you could easily spend thousands per month on a servers you don’t need in the meantime.

A Conservative approach can be just as effective. In most web hosting scenarios, you can upgrade your site to better hardware and be back online in no time. A few minutes, or even a couple hours downtime, while inconvenient can be tolerated if expected and planned for.

We will discuss this more in later chapters but this concept of expanding quickly to accommodate a change in traffic is known as “elasticity”.

In the next chapter we will ask the question “How do I pick a WordPress Host?”

Make WordPress AJAX Calls Cacheable and Improve WordPress Performance

WordPress Developers frequently make a very tiny but critical mistake when implementing wp_ajax calls that degrades WordPress performance and the scalability of  their website in cloud environments.

For instance, Daniel Pataki at WPMU offers a very clear and easy to follow tutorial on using the wp_ajax hook to make your web pages more dynamic. His example loads additional posts via an ajax-based pagination script. Very cool and very handy. Not only will it make you site more fun to use but also reduce overall server usage because the ajax call will be lighter weight than a full page view.

But once your site is on a modern cloud hosting infrastructure like WP Engine or Pantheon or Pagely, Daniel’s implementation will actually impede the performance benefits offered by these higher end hosts.

POST Requests Degrade WordPress Performance

Cloud hosts are usually running some sort of caching or “proxy”, usually Varnish, which dramatically speeds up your site load time. But POST requests are not going to get cached because it’s assumed that when POST’ing to a site your are performing a critical action like saving/submitting data.

But in the pagination example you’re just looking up what should be cacheable data. A GET request would allow the Varnish layer to serve that from cache much faster than would otherwise be possible. This also preserves your php resources for requests that actually need them and improves overall WordPress Performance.

Making this change is super simple (https://gist.github.com/mikevanwinkle/62fec97ac8cc8da5ff03):

		$.ajax({
 			url: ajaxpagination.ajaxurl,
-			type: 'post',
+			type: 'get',
 			data: {
 				action: 'ajax_pagination',
 				query_vars: ajaxpagination.query_vars,

WordPress Signal/Noise Ratio

I’ve decided to air some grievances about trends in the WordPress community that have me annoyed. Yesterday, I raised the issue of “freemium” plugins in the WordPress Repository. Today I want to bitch about the #wordpress twitter stream. There was a time when you could follow #wordpress and find real people exchanging ideas or asking questions or linking tutorials. It seems now though the community is a victim of it’s own success. To demonstrate my point yesterday I went through the first 50 tweets and broke them down by function:

34 tweets were directly selling something. And example might be

Visual Themify #Builder #WordPress #Plugin True #Drag #Drop #ThemeBuilder Design. Front- and Backend Design https://link/link

The link in the tweet above actually takes you to a hosting company website which is a bit misleading.

23 tweets were soft-selling. By this I mean they were tweets by a company to a blog post that was indirectly promoting their business or products. This is obviously preferable to the direct sell, but it still has some issues. For one thing, the quality of the content leaves much to be desired. I don’t find an article on “building an ecommerce site” that just lists a bunch of super-obvious steps, “First you need a domain, here’s a link to the domain affiliate that I profit from,” to be particularly valuable.

Only 3 articles had no obvious sales angle. This is a pathetic number. What’s worse is that many of the direct-sell tweets are just repeats of each other. At least 8 tweets ultimately linked back to one theme on the Envato Marketplace.

To be fair some of the issue here is without a doubt an issue with Twitter, not WordPress. And It’s hardly reasonable to expect WordPress to somehow curate the hashtag.

My concern though is that it is somewhat indicative of a trend in the WordPress ecosystem: it’s getting increasingly difficult to separate the cream from the crap.

Idea’s on this would be welcome.

It’s Time WordPress Establish Some Rules For Freemium Plugins

I’m not against developers providing “freemium” plugins in the official WordPress repository. By freemium, I mean a plugin that has some functionality restricted to entice you to purchase a license or premium version. Heck, I used to sell such a plugin myself.

But I do think it’s time for WordPress.org to enforce some general rules about how it’s handled. Two changes I would like to see that I think would be relatively easy to establish ( if not to enforce ).

  1. Take Apple’s lead in flagging apps that offer “in-app purchases” in the plugin directory. That way it’s immediately and visually discernible which plugins are fully functional and free and which are up-sellers. Ideally this would include the ability to hide freemiums in search results if desired.
  2. Nags to “upgrade” or “join” or respond to a survey–or any other sale related nag–should only appear in certain areas of the site. Obviously the plugin admin page is a reasonable place for the nags to happen. Maybe on the dashboard. But I should not experience nags on every page of the admin area. For example, the Types plugin:
    Screen Shot 2015-01-12 at 9.45.29 AM

WordPress 4.1 Out Tuesday, Hello TwentyFifteen

According to the official news, WordPress 4.1 will potentially drop on Tuesday. The most interesting changes are TwentyFifteen and the WP_Meta_Query optimizations which will help plugins that rely heavily on postmeta. A full list here.

To play critic for a moment. I’m not sure I like the new default theme. Not that I dislike it either. But I don’t have the oooohhhhh feeling I’ve had in previous years. Maybe thats because from the screenshots it doesn’t look much different than several themes already available. But maybe once I demo it’ll feel different.