4elements, Amsterdam, Holland

  1. Get Started Building Your Blog With Parse.js: User Login

    Final product image
    What You'll Be Creating

    In the last session, you learned how to add data on Parse.com and render it on your website. You got familiar with the concept of objects, collections, and views, and created your first class. From this session and moving forward, you will be creating the admin panel of the blog system. 

    And it all starts with creating a User class and enabling login.

    1. User Class

    Step 1: Add a User Class

    Parse.com made it extremely easy to add a new User class. Just click "Add Class" and choose "User" to create it.

    Add a User class

    Add a new row for yourself:

    Add a new user

    Step 2: Add Class-Level Access Controls

    Now that you have a user, we can make the application more secure by setting some class-level access permissions

    Go to your table for blog posts and click on "Security":

    Blog security

    Change the "Add Fields" permission from public to only yourself:

    Set permission

    This will prevent others from adding new fields to the table.

    Similarly, go to the User table and limit the "Add Fields" permission to yourself too. 

    You can set the rest of the class-level permissions according to your needs, but we will leave it for now.

    2. Prepare an Admin Page

    Step 1: Clean Up the Navigation

    First things first, let's clean up the navigation bar of the HTML template a little bit to make room for the new admin page. Change the <nav> element to have only two links: Home and Admin:

    <nav class="blog-nav">
        <a class="blog-nav-item active" href="index.html">Home</a>
        <a class="blog-nav-item" href="admin.html">Admin</a>
    </nav>

    Step 2: Prepare admin.html and Its CSS

    Then, duplicate index.html and rename it admin.html, and duplicate blog.js and rename it admin.js. (For those who are familiar with the concept of a router and hate duplicated code, please bear with me for a while. I promise you will eventually learn how to use a router and clean stuff up!)

    In admin.html, apply the .active class to the correct tab:

    <nav class="blog-nav">
        <a class="blog-nav-item" href="index.html">Home</a>
        <a class="blog-nav-item active" href="admin.html">Admin</a>
    </nav>

    And link to admin.js instead of blog.js:

    <script src="js/admin.js"></script>

    Make sure everything's still working well, and we can now move on to quickly throw together some HTML for a login page.

    Same old trick, go to http://getbootstrap.com/examples/signin, and copy the HTML of .form-signin into .main-container.

    <div class="main-container">
    	<form class="form-signin" role="form">
    		<h2 class="form-signin-heading">Please sign in</h2>
    		<input type="email" class="form-control" placeholder="Email address" required="" autofocus="">
    		<input type="password" class="form-control" placeholder="Password" required="">
    		<div class="checkbox">
    			<label>
    				<input type="checkbox" value="remember-me"> Remember me
    			</label>
    		</div>
    		<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    	</form>
    </div>

    Get the style in signin.css, and copy it into our blog.css, except for the style of body:

    .form-signin {
        max-width: 330px;
    	padding: 15px;
    	margin: 0 auto;
    }
    .form-signin .form-signin-heading,
    .form-signin .checkbox {
    	margin-bottom: 10px;
    }
    .form-signin .checkbox {
    	font-weight: normal;
    }
    .form-signin .form-control {
    	position: relative;
    	height: auto;
    	-webkit-box-sizing: border-box;
    	-moz-box-sizing: border-box;
    	box-sizing: border-box;
    	padding: 10px;
    	font-size: 16px;
    }
    .form-signin .form-control:focus {
    	z-index: 2;
    }
    .form-signin input[type="email"] {
    	margin-bottom: -1px;
    	border-bottom-right-radius: 0;
    	border-bottom-left-radius: 0;
    }
    .form-signin input[type="password"] {
    	margin-bottom: 10px;
    	border-top-left-radius: 0;
    	border-top-right-radius: 0;
    }

    Step 4: Clean Up admin.js

    Finally, get rid of everything in admin.js below Parse.initialize():

    $(function() {
    
        Parse.$ = jQuery;
    
        // Replace this line with the one on your Quickstart Guide Page
        Parse.initialize("HC87tn6aA7c3sYx9X0vwwLVXeqHDRMYYmrUBK5zv", "3piNGGnRMhvWo8u9pKD9TDc1MJlWhlvK78Vr3fHo");
    
    });

    Now refresh the page:

    Login page

    Looking good! 

    Step 5: Tweaking the Login Form

    Some final tweaks to the page: we will be using username to log in, so change the email field to a text field, and add the name attribute to both input fields:

    <input type="text" name="username" class="form-control" placeholder="Username" required="" autofocus="">
    <input type="password" name="password" class="form-control" placeholder="Password" required="">

    Change the CSS selector from email to text accordingly:

    .form-signin input[type="text"] {
        margin-bottom: -1px;
        border-bottom-right-radius: 0;
        border-bottom-left-radius: 0;
    }

    And get rid of the "Remember me" checkbox, because we are not planning to get into that in this tutorial.

    3. Enable Login

    Now we are finally ready to enable login. Let's write a bare-bones JavaScript function to log users in when they click on Submit in admin.js:

    $('.form-signin').on('submit', function(e) {
    
        // Prevent Default Submit Event
        e.preventDefault();
    
        // Get data from the form and put them into variables
        var data = $(this).serializeArray(),
            username = data[0].value,
            password = data[1].value;
    
        // Call Parse Login function with those variables
        Parse.User.logIn(username, password, {
            // If the username and password matches
            success: function(user) {
                alert('Welcome!');
            },
            // If there is an error
            error: function(user, error) {
                console.log(error);
            }
        });
    
    });

    Let's give it a try...

    Login success

    As simple as that: you are now logged in!

    4. Login View and Welcome View

    After you've logged in, you certainly don't want to just see an alert message and stay on the login page. We need to make a welcome screen for the logged-in users.

    To do that gracefully, we will make both a login and welcome page in Views and serve them with Parse.js.

    Step 1:  Make Templates

    Just as we did with the blog templates, let's take out everything in .main-container and make templates for the login page and the welcome page:

    <script id="login-tpl" type="text/x-handlebars-template">
        <form class="form-signin" role="form">
            <h2 class="form-signin-heading">Please sign in</h2>
            <input type="text" name="username" class="form-control" placeholder="Username" required="" autofocus="">
            <input type="password" name="password" class="form-control" placeholder="Password" required="">
            <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
        </form>
    </script>
    
    <script id="welcome-tpl" type="text/x-handlebars-template">
        <h2>Welcome, {}!</h2>
    </script>

    We can keep the welcome view very simple for now. It will just take the user object and display the username.

    Step 2: Define Views

    Let's define those views in admin.js. Notice that because LoginView doesn't need to render any object, the render function just puts the template HTML to the DOM.

    var LoginView = Parse.View.extend({
        	template: Handlebars.compile($('#login-tpl').html()),
    		render: function(){
    			this.$el.html(this.template());
    		}
    	}),
    	WelcomeView = Parse.View.extend({
    		template: Handlebars.compile($('#welcome-tpl').html()),
    		render: function(){
    			var attributes = this.model.toJSON();
    			this.$el.html(this.template(attributes));
    		}
    	});

    Step 3: Add Login Event to the View

    Remember the simple Login function we have? Now you can make that an event under LoginView:

    var LoginView = Parse.View.extend({
        template: Handlebars.compile($('#login-tpl').html()),
        events: {
            'submit .form-signin': 'login'
        },
        login: function(e) {
    
            // Prevent Default Submit Event
            e.preventDefault();
    
            // Get data from the form and put them into variables
            var data = $(e.target).serializeArray(),
                username = data[0].value,
                password = data[1].value;
    
            // Call Parse Login function with those variables
            Parse.User.logIn(username, password, {
                // If the username and password matches
                success: function(user) {
                    alert('Welcome!');
                },
                // If there is an error
                error: function(user, error) {
                    console.log(error);
                }
            });
        },
            render: function(){
            this.$el.html(this.template());
        }
    })

    Notice that we changed $(this).serializeArray() to $(e.target).serializeArray(). That's because in this context, this will point to LoginView.

    Step 4: Render Login View on the Page

    Before we move on to render the welcome view, let's first render a login view on the actual page and see if it works:

    var loginView = new LoginView();
    loginView.render();
    $('.main-container').html(loginView.el);

    Run it again, and it works just like before.

    Step 5: Render Welcome View in the Success Callback

    Now, let's change the success callback function of login() to render a welcome view using the returned user object.

    success: function(user) {
        var welcomeView = new WelcomeView({ model: user });
        welcomeView.render();
        $('.main-container').html(welcomeView.el);
    }

    Test again:

    Welcome screen

    And yay, it surely works!

    Conclusion

    In this session, you've created your second Class: the User Class. You've also created two important views: LoginView and WelcomeView. You also enabled user login on your website, and now you can send a personal welcome message to your users.

    This is just the starting point of building a blog admin panel. Stay tuned, and in the next tutorial we will create a new view and enable the "Add a new blog" function.

     

    0 Comments

    Leave a comment › Posted in: Daily

    1. The Beginner’s Guide to WordPress Taxonomies

      Let's say that you've recently started developing things with WordPress. Perhaps you've created basic theme or a plugin that does something simple, but you're ready to jump into more complex topics.

      This may include things such as custom meta boxes, the Settings API, custom post types, or using custom taxonomies. All of these are valuable things to learn and they each afford their own unique functionality within the overall context of WordPress.

      Some of these topics we've covered in detail before, some of them we've not. One of the topics that tends to give developers who are just starting out with WordPress development a little bit more trouble than others is the concept of taxonomies.

      In this series, we're going to be taking a beginner's look at taxonomies - from the concept to how they work in WordPress and from how we can use them in themes and plugins to implementing them in our own plugin.

      If you're an intermediate to experienced WordPress developer, then this series may not be suited for you; however, if you're a budding WordPress developer or someone who is looking to grow your expertise in an area that you've not previously worked with, then feel free to follow along with the rest of the series.

      Definition

      In order to start with the broadest possible idea of taxonomies, let's take a look the definition. According to Wikipedia:

      Taxonomy is the practice and science of classification.

      It sounds simple, right? In short, it's a way to classify things. But if that's the case, then why does the topic cause us trouble when working with WordPress?

      According to the WordPress Codex:

      Taxonomy is one of those words that most people never hear or use. Basically, a taxonomy is a way to group things together.

      And this definition isn't really altogether much different from what Wikipedia provided, is it? The common denominator between both of these definitions is that it's a way to group things together.

      That's it. That's the basic definition of taxonomy and that's what we need to understand in order to build out a working understanding of how they work within WordPress.

      Where Are They Used?

      Taxonomies are used throughout WordPress most prominently in two different ways:

      1. Categories
      2. Tags

      Every base installation ships with these particular features for the standard post type, and many of us use them on a daily basis either when working with our own blog, managing someone else's blog, or perhaps building a site for someone using WordPress.

      If you're brand new to WordPress, then you should know the following:

      • A category taxonomy allows you to group posts together in under a common category. For example, you may grow some posts under Videos and other posts under Photographs.
      • A tag taxonomy allows us to similarly classify our content, but in a slightly less structured way. For example, under Videos, you may tag your videos using tags that are related to the frame rate of the video. This wouldn't make sense as a category because photographs don't have frame rates.

      You can think of categories as being more structured and tags as being more free form (or simply less structured), but that still raises questions as to how they fit within WordPress and how we can actually go about creating some type of conceptual model for taxonomies.

      How Do We Classify Them?

      It's helpful to think of taxonomies in two forms: Hierarchical and Non-Hierarchical.

      Hierarchical

      The most common example of a hierarchical taxonomy is a category. A hierarchical taxonomy is one that can exist a single taxonomy on its own, or it can have children, grand-children, and great-grand-children elements.

      The basic hierarchical - or category - taxonomy that ships with WordPress is Uncategorized. But let's say you were building out a media site with photos and videos. From here, you may have two categories: Photographs and Videos

      Then, under Photographs you may have Outdoor, Lifestyle, Families, Children, and/or Weddings. For your videos, you  may have High-Definition, People, Wildlife, Film, and so on. 

      If you were to see this in the WordPress dashboard, it may look something like this:

      • Photographs
        • Outdoor
        • Lifestyle
        • Families
        • Children
        • Weddings
      • Videos
        • High-Definition
        • People
        • Wildlife
        • Film

      Of course, you could have each of the child categories have their own children. For example, the Videos High-Definition could have 720p and 1080p. As you can see, hierarchical taxonomies work best when there is a clear way that you're going to be organizing your information. 

      Sometimes, a good way to think of a real world example of a hierarchical taxonomy is through the use of a filing cabinet with drawers and then folders that fit inside each of the drawers. In our case, Photographs would be a filing cabinet, Outdoor, Lifestyle, etc. would be the drawers. If you were to have another level of categorization, those could be folders inside the drawer.

      Non-Hierarchical

      But what about non-hierarchical taxonomies? The most common example of these is a tag. A non-hierarchical taxonomy is one that exists all on its own. There's no notion of children and they can be added easily and freely to posts (and may co-exist with categories).

      Building on our previous example, let's say that your Photographs and your Videos are divided into Black and White or Color. Though these could work as categories, they also work as tags in that they can apply to both photographs and videos.

      Just as we think about categories as a filing cabinet with drawers, sometimes it's helpful to think of tags as stamps or labels - an way in which an existing item, category, or even sub-category is identified with similar content.

      Say that we have our filing cabinet - one cabinet for Photographs and one cabinet for Videos. Then inside each of those cabinets are drawers. For the former, we have drawers for Outdoor, Lifestyle, Families, and so on, and for the latter we have High-Definition, People, Wildlife, and so on.

      Then, let's say that each item in those drawers are identified as either Color or Black and White. You may also want to stamp each photo with a season, a year, a location, and so on. Anyway, each item would have perhaps a label, a stamp, a post-it note, or a tab to indicate the type of film that was used to shoot the subject matter.

      From a technical perspective, this gives us the ability to pull back all Videos and Photographs that are Colored as well as allows us to pull back just Wildlife videos that are in Black and White.

      The combinations that you can use to retrieve this information gets more and more complex - and powerful - based on the amount of information that you have classified.

      Up Next

      With this introduction in place, we're ready to turn our attention to a more technically focused approach to working with taxonomies. That is, we're ready to look at taxonomies within the context of themes and plugins, when it's appropriate to use which, where, and why, and how compatibility factors into the conversation.

      After that, we'll look at implementing the taxonomies that we've outlined in this article via the WordPress API into a working example that you can download and install in your local version of WordPress in order to read the code, tinker with the code, and review the code to give you a concrete understanding of how to use the code in your work moving forward.

       

      0 Comments

      Leave a comment › Posted in: Daily

    1. Digging in to Laravel’s IoC Container

      Inversion of Control, or IoC, is a technique that allows control to be inverted when compared to classical procedural code. The most prominent form of IoC is, of course, Dependency Injection, or DI. Laravel's IoC container is one of the most used Laravel features, yet is probably the least understood.

      Here's a very quick example of using Dependency Injection to achieve Inversion of Control.

      <?php
      
      class JeepWrangler
      {
          public function __construct(Petrol $fuel)
          {
              $this->fuel = $fuel;
          }
      	
          public function refuel($litres)
          {
      	    return $litres * $this->fuel->getPrice();
          }
      }
      
      class Petrol
      {
          public function getPrice()
          {
          	return 130.7;
          }
      }
      
      $petrol = new Petrol;
      $car = new JeepWrangler($petrol);
      
      $cost = $car->refuel(60);

      By using constructor injection we have now delegated creation of our Petrol instance back to the caller itself, thus achieving inversion of control. Our JeepWrangler does not need to know where the Petrol comes from, so long as it gets it.

      So what does all this have to do with Laravel? Quite a lot, actually. Laravel, if you didn't know, is actually an IoC container. A container is an object that, as you may expect, contains things. Laravel's IoC container is used to contain many, many different bindings. Everything you do in Laravel will at some point have an interaction with the IoC container. This interaction is generally in the form of a binding being resolved.

      If you open up any of the existing Laravel service providers, you'll most likely see something like this in the register method (example has been simplified, a lot).

      $this->app['router'] = $this->app->share(function($app) {
          return new Router;
      });

      That is a very, very basic binding. It consists of the name of the binding (router) and a resolver (the closure). When that binding is resolved from the container we will get an instance of Router returned.

      Laravel usually groups similar binding names, such as session and session.store.

      To resolve the binding we can simply call a method directly off it, or use the make method on the container.

      $router = $this->app->make('router');

      That is what the container does in its most basic form. But, like most things Laravel, there's a whole lot more to it than just binding and resolving classes.

      Shared and Non-Shared Bindings

      If you've looked through several of the Laravel service providers, you'll notice that most bindings are defined like the earlier example. Here it is again:

      $this->app['router'] = $this->app->share(function($app) {
          return new Router;
      });

      This binding uses the share method on the container. Laravel uses a static variable to store a previous resolved value and will simply reuse that value when a binding is resolved again. This is basically what the share method does.

      $this->app['router'] = function($app) {
          static $router;
      	
          if (is_null($object)) {
              $router = new Router;
          }
      	
      	return $router;
          
      };

      Another way of writing this would be to use the bindShared method.

      $this->app->bindShared('router', function($app) {
          return new Router;
      });

      You can also use the singleton and instance methods to achieve a shared binding. So, if they all achieve the same thing, what's the difference? Not a whole lot, actually. I personally prefer to use the bindShared method.

      Conditional Binding

      There may be times when you want to bind something to the container, but only when it hasn't already been bound before. There are a few ways you could go about this, but the easiest is to use the bindIf method.

      $this->app->bindIf('router', function($app) {
          return new ImprovedRouter;
      });

      This will only bind to the container if the router binding does not already exist. The only thing to be aware of here is how to share a conditional binding. To do so, you need to supply a third parameter to the bindIf method with a value of true.

      Automatic Dependency Resolution

      One of the most commonly used features of the IoC container is its ability to automatically resolve dependencies for classes that are not bound. What does this mean, exactly? First off, we don't actually need to bind something to the container to resolve an instance. We can simply make an instance of just about any class.

      class Petrol
      {
          public function getPrice()
          {
              return 130.7;
          }
      }
      
      // In our service provider...
      $petrol = $this->app->make('Petrol');

      The container will instantiate our Petrol class for us. The best part about this is that it will also resolve constructor dependencies for us.

      class JeepWrangler
      {
          public function __construct(Petrol $fuel)
          {
              $this->fuel = $fuel;
          }
      	
          public function refuel($litres)
          {
              return $litres * $this->fuel->getPrice();
          }
          
      }
      
      // In our service provider...
      $car = $this->app->make('JeepWrangler');

      The first thing the container does is inspect the dependencies of the JeepWrangler class. It will then attempt to resolve those dependencies. So, because our JeepWrangler type-hints the Petrol class, the container will automatically resolve and inject it as a dependency.

      The container can't automatically inject non-type-hinted dependencies. So if one of your dependencies is an array, then you'll need to instantiate it manually or give the parameter a default value.

      Binding Implementations

      Having Laravel automatically resolve your dependencies is great and simplifies the process of instantiating classes manually. However, there are times when you want a specific implementation to be injected, especially when you're using interfaces. This is easily achieved by using the fully qualified name of the class as the binding. To demonstrate this we'll be using a new interface called Fuel.

      interface Fuel
      {
          public function getPrice();
      }

      Now our JeepWrangler class can type-hint the interface, and we'll make sure that our Petrol class implements the interface.

      class JeepWrangler
      {
          public function __construct(Fuel $fuel)
          {
              $this->fuel = $fuel;
          }
      	
          public function refuel($litres)
          {
              return $litres * $this->fuel->getPrice();
          }
      }
      
      class Petrol implements Fuel
      {
          public function getPrice()
          {
              return 130.7;
          }
      }

      We can now bind our Fuel interface to the container and have it resolve a new instance of Petrol.

      $this->app->bind('Fuel', 'Petrol');
      
      // Or, we could instantiate it ourselves.
      $this->app->bind('Fuel', function ($app) {
          return new Petrol;
      });

      Now when we make a new instance of our JeepWrangler, the container will see that it asks for Fuel, and it will know to automatically inject an instance of Petrol.

      This also makes it really easy to swap out an implementation, as we can simply change the binding in the container. To demonstrate, we might start refueling our car with premium petrol, which is a little more expensive.

      class PremiumPetrol implements Fuel
      {
          public function getPrice()
          {
              return 144.3;
          }
      }
      
      // In our service provider...
      $this->app->bind('Fuel', 'PremiumPetrol');

      Contextual Bindings

      Note that contextual bindings are only available in Laravel 5.

      A contextual binding allows you to bind an implementation (much like we did above) to a specific class.

      abstract class Car
      {
          public function __construct(Fuel $fuel)
          {
              $this->fuel = $fuel;
          }
      
          public function refuel($litres)
          {
              return $litres * $this->fuel->getPrice();
          }
      }

      We'll then create a new NissanPatrol class that extends the abstract class, and we'll update our JeepWrangler to extend it as well.

      class JeepWrangler extends Car
      {
          //
      }
      
      class NissanPatrol extends Car
      {
          //
      }

      Lastly we'll create a new Diesel class that implements the Fuel interface.

      class Diesel implements Fuel
      {
          public function getPrice()
          {
              return 135.3;
          }
      }

      Now, our Jeep Wrangler will refuel using petrol and our Nissan Patrol will refuel using diesel. If we tried to use the same method as before by binding an implementation to the interface, then both of these cars would get the same type of fuel, which isn't what we want.

      So to make sure each car refuels with the correct fuel, we can inform the container which implementation to use in each context.

      $this->app->when('JeepWrangler')->needs('Fuel')->give('Petrol');
      $this->app->when('NissanPatrol')->needs('Fuel')->give('Diesel');

      Tagging

      Note that tagging is only available in Laravel 5.

      Being able to resolve bindings from the container is pretty important. Normally we can only resolve something if we know how it's been bound to the container. With Laravel 5, we're now able to tag our bindings so that developers can easily resolve all bindings that have the same tag.

      If you're developing an application that allows other developers to build plugins and you want to be able to easily resolve all of those plugins, tags will be extremely useful.

      $this->app->tag('awesome.plugin', 'plugin');
      
      // Or an array of tags.
      
      $tags = ['plugin', 'theme'];
      
      $this->app->tag('awesome.plugin', $tags);

      Now, to resolve all the bindings for a given tag we can use the tagged method.

      $plugins = $this->app->tagged('plugin');
      
      foreach ($plugins as $plugin) {
          $plugin->doSomethingFunky();
      }

      Rebounds and Rebinding

      When you bind something to the container with the same name more than once, it's called rebinding. Laravel will notice you binding something again and will trigger a rebound.

      The biggest benefit here is when you're developing a package that allows other developers to extend it by rebinding components in the container. To use it we'll need to implement setter injection on our Car abstract.

      abstract class Car
      {
          public function __construct(Fuel $fuel)
          {
              $this->fuel = $fuel;
          }
      
          public function refuel($litres)
          {
              return $litres * $this->fuel->getPrice();
          }
          
          public function setFuel(Fuel $fuel)
          {
              $this->fuel = $fuel;
          }
          
      }

      Let's assume we're binding our JeepWrangler to the container like so.

      $this->app->bindShared('fuel', function ($app) {
          return new Petrol;
      });
      
      $this->app->bindShared('car', function ($app) {
      	return new JeepWrangler($app['fuel']);
      });

      This is perfectly fine, but let's say another developer comes along and wants to extend this and use premium petrol in the car. So they use the setFuel method to inject their new fuel into the car.

      $this->app['car']->setFuel(new PremiumPetrol);

      In most cases, this might be all that's needed; however, what if our package gets more complicated and the fuel binding is injected into several other classes? This would result in the other developer having to set their new instance a whole bunch of times. So, to solve this, we can make use of rebinding:

      $this->app->bindShared('car', function ($app) {
          return new JeepWrangler($app->rebinding('fuel', function ($app, $fuel) {
      		$app['car']->setFuel($fuel);
      	}));
      });

      The rebinding method will immediately return to us the already bound instance so we're able to use it in the constructor of our JeepWrangler. The closure given to the rebinding method receives two parameters, the first being the IoC container and the second being the new binding. We can then use the setFuel method ourselves to inject the new binding into our JeepWrangler instance.

      All that's left is for another developer to simply rebind fuel in the container. Their service provider might look like this:

      $this->app->bindShared('fuel', function () {
          return new PremiumPetrol;
      });

      Once the binding is rebound in the container, Laravel will automatically trigger the associated closures. In our case the new PremiumPetrol instance will be set on our JeepWrangler instance.

      Extending

      If you want to inject a dependency into one of the core bindings or a binding created by a package, then the extend method on the container is one of the easiest ways to go about it. 

      This method will resolve the binding from the container and execute a closure with the container and the resolved instance as parameters. This allows you to easily resolve and inject your own bindings, or simply instantiate a new class and inject it.

      $this->app->extend('car', function ($app, $car) {
          $car->setFuel(new PremiumPetrol);
      });

      Unlike rebinding, this will only set the dependency on a single binding.

      Usage Outside Laravel

      Like many of the Illuminate components that make up the Laravel framework, the Container can be used outside Laravel in a standalone application. To do so, you must first require it as a dependency in your composer.json file.

      {
          "require": {
              "illuminate/container": "4.2.*"
         }
      }

      This will install the latest 4.2 version of the container. Now, all that's left to do is instantiate a new container.

      require 'vendor/autoload.php';
      
      $app = new Illuminate\Container\Container;
      
      $app->bindShared('car', function () {
          return new JeepWrangler;
      });

      Of all the components, this is one of the easiest to use wherever you need a flexible and featured IoC container.

       

      0 Comments

      Leave a comment › Posted in: Daily

    1. 50 Filters of WordPress: Series Finale

      Welcome to the series finale of "50 Filters of WordPress"! In this last part, we're going to review what we learned and summarize all the 50 filters with 10 words (give or take) each.

      Let's begin!

      First Part An Introduction to WordPress Filters

      In the first part of the series, we entered the magical world of WordPress filters and got to know what they are, how they work, when we should use them and how we should use them. We learned:

      What a WordPress filter is: A filter is a function that sits between the database and the browser, doing stuff to your data before WordPress outputs it. WordPress has—literally—hundreds of filters inside its core and you can create your own filters in the things you develop (like plugins). That's what we learned.

      How to create a filtering function and hook it to a filter: It's simple in essence, really: We create a function that plays with the data and we hook it to the corresponding filter hook by using the add_filter() function. (I might have over-simplified it – it's actually a bit more complicated than that.) Be sure to check out the first part of this series, if you haven't already. It's important.

      How to remove a function (or functions) from a filter: We learned two functions in WordPress to remove functions from filters: remove_filter() and remove_all_filters(). (You can probably guess which one removes one function and which one removes all functions hooked to a filter.) We learned how to use these functions.

      How to create our own filters: WordPress has hundreds of awesome filters in its core, but what if we need our plugin to be as flexible and expandable as the core? Well, we create our own filter hooks by using the apply_filters() function. Be sure to check that out, too, if you're a plugin developer.

      Next Five Parts 50 Great Examples for 50 Great Filters

      After entering the world of WordPress filters, the best thing to do would have been getting to know about each and every filter hook in WordPress' core. While that would be the most amazing tutorial series in the history of WordPress tutorials, it would take an incredible amount of time and effort because there are a little over a thousand filters in the core as of WordPress v3.9.1.

      That doesn't mean we should sit and learn nothing, though. I chose 50 WordPress filters, introduced them with little paragraphs and done examples with each one. Here's what we learned with brief explanations:

      50 Examples for WordPress Filters – Part Two

      1. login_errors allows us to change the error messages while logging in to WordPress.
      2. comment_post_redirect makes it possible for us to redirect visitors to an internal page (or an allowed external web page) after they post a comment.
      3. allowed_redirect_hosts lets us define "safe" external hosts for the wp_safe_redirect() function.
      4. body_class gives us the opportunity to set custom class names for the <body> tag.
      5. locale makes WordPress change its language.
      6. sanitize_user cleans up the usernames and lets us change the cleaning up sequence.
      7. the_content filters the post contents amd allows us to intervene before the contents are displayed.
      8. the_password_form creates the password forms for password protected posts and lets us change the form.
      9. the_terms filters the output of the the_terms() function and again, lets us intervene.
      10. wp_mail_from allows us to change the "From" name of the emails WordPress sends.

      50 Examples for WordPress Filters – Part Three

      1. gettext filters the translatable strings so we can tamper with the behaviour or change the strings.
      2. sanitize_title cleans up the post titles in order to save them as "slugs" and allows us to alter the process.
      3. no_texturize_shortcodes gives us the chance to add our shortcodes to the "do not texturize" list.
      4. pre_comment_approved filters the process before a comment is approved (or not) and lets us step in.
      5. enable_post_by_email_configuration lets us enable or disable the "post by email" feature of WordPress core.
      6. wp_title filters the page titles, normally shown in the <title> tags and on our tab handles in our browsers.
      7. preprocess_comment handles the processes before any comment data is saved to the database.
      8. login_redirect makes it possible for us to set a "safe" redirect after a user logs in.
      9. plugin_action_links_$plugin allows us display links under our plugin names in the Plugins page.
      10. the_editor_content gives us the opportunity to pre-fill the content of the post editor which is empty by default.

      50 Examples for WordPress Filters – Part Four

      1. use_default_gallery_style lets us enable or disable the default CSS rules for the [gallery] shortcode.
      2. wp_get_attachment_url filters the output of attachment URLs and allows us to step in.
      3. wp_mail_content_type allows us to change the content type of emails that WordPress sends (which is text/plain by default).
      4. pre_comment_user_ip makes it possible for us to tamper with the IP address of commenters before the addresses are saved to the database.
      5. wp_revisions_to_keep lets us change the revisions limit for posts – a single post, post types or whatever you can imagine!
      6. img_caption_shortcode filters the core [caption] shortcode for images and lets us rewrite the output completely, if necessary.
      7. post_class filters the post_class() function and makes it possible to set custom class names for posts.
      8. attachment_fields_to_edit allows us to add or remove input fields for attachments.
      9. excerpt_length lets us change how many words will be displayed for automatic excerpts.
      10. bulk_actions-$screenid filters the bulk actions for the item lists in admin pages and lets us add or remove actions.

      50 Examples for WordPress Filters – Part Five

      1. posts_search filters the searching process and allows us to intervene.
      2. wp_editor_set_quality sets the compression quality for resized attachment images and lets us change that setting.
      3. widget_text filters the default Text widget and allows us to tamper with the output.
      4. the_content_feed makes it possible for us to change the feed items' content.
      5. mce_buttons lets us add or remove buttons for the first line of our Visual Editors.
      6. list_terms_exclusions gives us the opportunity to define exceptions in terms lists.
      7. image_size_names_choose allows us to add custom image size names for the "Sizes" dropdown shown when an image is added in the Visual Editor.
      8. excerpt_more lets us change the default [...] text to something else for automatic excerpts.
      9. manage_posts_columns makes it easier for us to edit the columns of post lists in admin pages.
      10. user_contactmethods makes it possible for us to add or remove profile input fields.

      50 Examples for WordPress Filters – Part Six

      1. script_loader_src filters the wp_enqueue_script() function and lets us step in with the function's output.
      2. admin_post_thumbnail_html allows us to add HTML after the "Set featured image" link on the "New Post" page.
      3. comment_flood_filter gives us the opportunity to tamper with the flood checking process.
      4. dashboard_glance_items lets us change the "At a Glance" section in the admin dashboard.
      5. login_message gives us the possibility to change the default login messages.
      6. bulk_post_updated_messages filters the output of the informational messages when a post is updated.
      7. widget_categories_args makes it possible for us to play with the arguments of the default Categories widget.
      8. registration_redirect allows us to set a "safe" redirect upon a successful registration.
      9. comment_form_default_fields lets us play with the default comment form fields.
      10. upload_mimes makes it easier for us to change the allowed list of file types that can be uploaded to the Media Library.

      The End

      So that's the end of it. We're done with the series of WordPress filters – but we're not done with WordPress hooks yet: Stay tuned for another seven-part tutorial on WordPress actions!

      Despite the fact that it was the most exhausting series of tutorials, I enjoyed writing every word and every bit of code for I knew it would be a small—but extremely useful—resource on this topic. I learned a lot while writing; I just hope you did as well.

      All kinds of contribution will be appreciated, by the way. You can:

      1. Share your thoughts on this series by commenting below,
      2. Suggest new filters and example ideas for an "addendum" part or two,
      3. Offer ways to improve my writing if you caught a mistake, incoherency or ambiguity in my posts,
      4. And share these tutorials anywhere for everyone to see and learn about WordPress filters!

      Thanks for bearing with me till the end. Goodbye!

       

      0 Comments

      Leave a comment › Posted in: Daily

    1. A Comprehensive Approach to Magento SEO: The Basics

      This is the first part of a four-article series in which we'll explore Magento Search Engine Optimization techniques in detail. In this article, you'll learn how to develop an effective keyword strategy for your Magento website, some general Magento admin panel configurations to make it more SEO friendly, how to create the robot.txt and sitemap.xml files, and how to set up Google Analytics for a Magento store.

      One of the hallmarks of Magento, which distinguishes it from other eCommerce CMSs, is the extent of customization it offers. In Magento, unlike most other eCommerce CMSs, we have the flexibility to customize every page, every product, and every snippet of code within its framework for search engines. 

      In this series, we’ll cover all the fundamentals you need to know to best equip your Magento website to rank well in search engine result pages, giving a boost to your sales and revenues.

      Planning a Keyword Strategy

      All SEO optimization campaigns start with effective planning of a keyword strategy. This is also true when it comes to eCommerce platforms. While planning a keyword strategy for an eCommerce platform, we have to maintain an effective balance between three important factors:

      1. Relevance means that the page optimized for specific keyword(s) should have relevant content on it. 
      2. Purpose implies that the content of the page should also direct users towards the ultimate purpose of the website, i.e. to drive sales.
      3. Structure means that page's authority from an SEO perspective is inversely proportional to its depth in the website structure. Therefore, the homepage has more authority than a product or CMS page. Hence, a homepage should be optimized for more broad and competitive keywords, while the pages deep in the website structure should be optimized for more specific and less competitive keywords.
      Planning a keyword strategy for SEO

      To have an effective keyword strategy, we have to consider each of these three factors. We have to ensure that our keyword resides on the page with enough strength to enable to it to perform, and we also have to guarantee that it is sufficiently relevant to the page’s content to keep the visitor engaged. This should all help in accomplishing the main purpose of the website.

      Magento Admin Panel Configurations for SEO

      Once we have an effective keyword strategy developed, it’s time to start preparing our Magento store for Search Engine Optimization. The first place to start is with the Magento admin panel configurations, as they are the easiest and quickest configurations to update.

      First of all, we’ll go to Magento Admin Panel > System > Configuration > Web. Here, from the URL Options tab, we’ll change the Auto-redirect to Base URL to Yes (301 Moved Permanently). This will remove the redundant index.php that is appended to the base URL. 

      Then, from the Search Engine Optimization tab, we’ll change Use Web Server Rewrites to Yes. This will auto-redirect to the base URL in case the domain is typed without the "www" prefix.

      URL options

      Next we’ll make a couple of changes in System > Configuration > Catalog > Search Engine Optimizations. Here you’ll see these default settings:

      Default Magento SEO settings

      On this screen, we’ll set Use Categories Path for Product URLs to No. The rationale behind this is that products can be accessed from two different URLs in Magento:

      1. With a category name in the URL, like http://myexamplestore.com/category/subcategory/product.html
      2. Without a category name in the URL, like http://myexampledomain.com/product.html

      When a search crawler accesses the same page through two different URLs, it thinks we are duplicating content across two pages. By setting Use Categories Path for Product URLs to No, we disable the product path with the category name in the URL, thus leaving only one path to access the product page. This will help us avoid duplicate content penalties. 

      To further reduce the chances of duplicate content penalties, we’ll turn Use Canonical Link Meta Tag for Categories and Use Canonical Link Meta Tag for Products to Yes. A more in-depth explanation about canonical tags will be provided in the next article in this series.

      Our next step will be to define store default settings for title, description, and keywords. Magento uses a fallback approach to determine the value of these tags. 

      First, it will look to see if any category or CMS page has specifically defined values for these tags. If it finds them, it will use them as first preference. If there is no such tag specifically defined for an individual category or CMS page, it will try to populate these itself by resorting to store default settings. 

      For products, however, it uses a different approach. For products it pre-populates product name as "title", product description as "description" and product name as "keyword". To edit the default settings, go to System > Configuration > Design > HTML Head.

      HTML Head settings in Magento

      On the same page you’ll see settings for Default Robots. Select INDEX, FOLLOW from the drop-down to allow search engines to index your store’s web pages and follow the links found therein.

      Setting Up an XML Sitemap

      Creating a well-structured XML sitemap is a long-established practice to make it easier for search engines to index the pages of the website. Creating and maintaining the XML sitemap of an eCommerce website can be a particularly daunting task, as there could be thousands of products, under hundreds of categories and subcategories. 

      To make this possible for its users, the Magento team has created an XML sitemap generator within Magento. To configure Magento Sitemap, go to System > Configuration > Google Sitemap and configure the Frequency and the Priority of sitemap generation.

      For most eCommerce websites, the first priority should be given to the category pages, as they serve as the main landing pages for most search terms. Next in priority come the product pages, which users reach if they search for a particular product. Last in priority are the CMS pages, which contain static content for the website. 

      For the update frequency, I would recommend having your category and products updated on a daily basis in sitemap, while the CMS pages could be updated on a weekly basis, as changes don’t occur in them very frequently. In a nutshell, your sitemap settings should look broadly like the below screenshot. 

      If you think you add/edit new products or categories much less often than that, you can modify these settings accordingly.

      Google Sitemap settings in Magento

      Once the correct XML Sitemap settings are in place, the next step is to generate the sitemap. For this, go to Catalog > Google Sitemap and click on Add Sitemap. Enter any file name of your choice, e.g.  sitemap.xml, and for Path just enter /, as we want to place the sitemap at the root URL. 

      Now hit the Save and Generate button.

      Add a new sitemap in Magento

      To verify that you have a working sitemap in place, visit the sitemap URL to confirm, e.g. http://myexamplestore.com/sitemap.xml.

      Robot.txt Settings

      robot.txt files are particularly important as the main way of communicating with search engine crawlers. Through the robot.txt file, we can tell search engines which pages to index and follow and which pages to avoid. Some other important information like the location of the sitemap is also communicated via the robot.txt file.

      In order to prepare our robot.txt file for our Magento installation, first of all we’ll make sure that search engines notice and keep track of our sitemap file. To accomplish this, we'll add this line in our robot.txt file:

      Sitemap: http://www.myexamplestore.com/sitemap.xml

      Next, we want to stop search engines from crawling our checkout, review, and catalog search pages. To do this we’ll add these lines into our robot.txt file:

      Disallow: /checkout/
      Disallow: /review/
      Disallow: /catalogsearch/

      Now, to avoid duplicate content penalties, we’ll add these two lines as well, to avoid indexing of duplicate pages of categories and products:

      Disallow: /catalog/product/view/
      Disallow: /catalog/category/view/

      Configuration for Google Analytics

      Tracking traffic is a crucial part of any successful web venture. Google Analytics is the most popular and widely used analytics tool in the web industry. To track which keywords are generating most traffic, which products are getting most sales, and numerous other such statistics, we’ll integrate Google Analytics into our Magento installation. 

      Sign up for Google Analytics if you don’t already have an account. Create a new property, and identify its property tracking number by opening up the relevant property, clicking on the Admin tab at the top, and on the next page clicking on Property Settings.

      Google Analytics Property Settings

      The next step is to enable eCommerce tracking in your Google Analytics account. For this, again click on the Admin tab, select Ecommerce Settings, and change the status to ON.

      Set Google Analytics Ecommerce Settings to On

      Now the last step is to enter that tracking number into Magento and to enable tracking. For this purpose we’ll go to System > Configuration > Google API > Google Analytics. Here enter the tracking number, and enable it. Don’t forget to hit Save Config at the end.

      Enable Google Analytics in Magento

      Coming Up Next

      With all these steps completed, we have built a fairly good SEO foundation for our Magento store. 

      In the next parts of this series, I’ll guide you further on how to improve your Magento website from an SEO perspective. At the end of the series, I hope you’ll have a fully SEO-optimized Magento website.

      Please leave your feedback and questions in the comments!

       

      0 Comments

      Leave a comment › Posted in: Daily

  • Page 1 of 36 pages  1 2 3 >  Last ›
  • Browse the Blog

    Syndicate

    governing-bruise