Enabling you to develop the best web. tools and method for you. HTML ,CSS ,CODE ,websigns ,,webdevelopment
Wednesday, November 30, 2016
Tuesday, November 29, 2016
How to Run Unix Commands in Your Python Program
Unix is an operating system which was developed in around 1969 at AT&T Bell Labs by Ken Thompson and Dennis Ritchie. There are many interesting Unix commands we can use to carry out different tasks. The question is, can we use such commands directly within a Python program? This is what I will show you in this tutorial.
The Unix command ls lists all files in the directory. If you put ls as is in a Python script, this is what you will get when you run the program:
Traceback (most recent call last):
File "test.py", line 1, in <module>
ls
NameError: name 'ls' is not defined
This shows that the Python interpreter is treating ls as a variable and requires it to be defined (i.e. initialized), and did not treat it as a Unix command.
os.system()
One solution to this issue is to use os.system() from Python’s os module.
As mentioned in the documentation, os.system():
Executes the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations.
So, we can run the ls command in Python as follows:
import os
os.system('ls')
This will return the list of files in your current directory, which is where your .py program is located.
Let’s take another example. If you want to return the current date and time, you can use the Unix command date as follows:
import os
os.system('date')
In my case, this was what I got as a result of the above script:
Tue May 24 17:29:20 CEST 2016
call()
Although os.system() works, it is not recommended as it is considered a bit old and deprecated. A more recommended solution is Python’s subprocess module call(args) function. As mentioned in the documentation about this function:
Run the command described by args. Wait for command to complete, then return the returncode attribute.
If we want to run the ls Unix command using this method, we can do the following:
from subprocess import call
call('ls')
Let’s see how we can return the date using the subprocess module, but let’s make the example more interesting.
import subprocess
time = subprocess.Popen('date', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err = time.communicate()
print 'It is', output
The above example can be run more simply using check_output(), as follows:
import subprocess
time = subprocess.check_output('date')
print 'It is', time
The output of the above scripts is:
It is Tue May 24 19:14:22 CEST 2016
The above examples show the flexibility in using different subprocess functions, and how we can pass the results to variables in order to carry out further operations.
Conclusion
As we saw in this tutorial, Unix commands can be called and executed using the subprocess module, which provides much flexibility when working with Unix commands through its different functions. You can learn more about this module and its different functions from the Python documentation.
Monday, November 28, 2016
Sunday, November 27, 2016
Saturday, November 26, 2016
Friday, November 25, 2016
Object-Oriented Autoloading in WordPress, Part 2
In the previous tutorial, we covered a handful of concepts, all of which are going to be necessary to fully understand what we're doing in this tutorial.
Specifically, we covered the following topics:
- object-oriented interfaces
- the single responsibility principle
- how these look in PHP
- where we're headed with our plugin
In some series, it's easy to skip tutorials that may not build on one another; however, this series isn't intended to be like that. Instead, it's meant to be read in sequential order, and it's meant to build on the content of each previous tutorial.
With that said, I'm assuming you're all caught up.
Getting Started
Even though I might have mentioned this in the first tutorial, I still like to make sure we're all on the same page with regard to what we're doing in each tutorial and with what software you're going to need.
Our Roadmap
So in this tutorial, the plan is as follows:
- Examine the code that we have written thus far.
- Determine how we may be able to refactor it using object-oriented techniques.
- Provide the high-level outline for our implementation.
Ultimately, we won't be writing much code in this tutorial, but we'll be writing some. It is, however, a practical tutorial in that we're performing object-oriented analysis and design. This is a necessary phase for many large-scale projects (and something that should happen for small-scale projects).
What You Need
If you've been following along, you should have this already set up. But to make sure, here's the short version of everything you need:
- a local development environment suitable for your operating system
- a directory out of which WordPress 4.6.1 is being hosted
- a text editor or IDE
- knowledge of the WordPress Plugin API
With all of that in place, we're ready to work on the code shared in the previous tutorial. So let's get started.
Analyzing the Code
The very first thing we want to do is analyze the current state of our autoloader. It might seem like a lot of code to paste into a single block of code, but that in and of itself shows us that we have some work to do.
With that said, here's the current state of our autoloader:
<?php
function tutsplus_namespace_demo_autoload( $class_name ) {
// If the specified $class_name does not include our namespace, duck out.
if ( false === strpos( $class_name, 'Tutsplus_Namespace_Demo' ) ) {
return;
}
// Split the class name into an array to read the namespace and class.
$file_parts = explode( '\\', $class_name );
// Do a reverse loop through $file_parts to build the path to the file.
$namespace = '';
for ( $i = count( $file_parts ) - 1; $i > 0; $i-- ) {
// Read the current component of the file part.
$current = strtolower( $file_parts[ $i ] );
$current = str_ireplace( '_', '-', $current );
// If we're at the first entry, then we're at the filename.
if ( count( $file_parts ) - 1 === $i ) {
/* If 'interface' is contained in the parts of the file name, then
* define the $file_name differently so that it's properly loaded.
* Otherwise, just set the $file_name equal to that of the class
* filename structure.
*/
if ( strpos( strtolower( $file_parts[ count( $file_parts ) - 1 ] ), 'interface' ) ) {
// Grab the name of the interface from its qualified name.
$interface_name = explode( '_', $file_parts[ count( $file_parts ) - 1 ] );
$interface_name = $interface_name[0];
$file_name = "interface-$interface_name.php";
} else {
$file_name = "class-$current.php";
}
} else {
$namespace = '/' . $current . $namespace;
}
}
// Now build a path to the file using mapping to the file location.
$filepath = trailingslashit( dirname( dirname( __FILE__ ) ) . $namespace );
$filepath .= $file_name;
// If the file exists in the specified path, then include it.
if ( file_exists( $filepath ) ) {
include_once( $filepath );
} else {
wp_die(
esc_html( "The file attempting to be loaded at $filepath does not exist." )
);
}
}
At this point, remember that the single responsibility principle states the following:
A class should have only one reason to change.
Right now, we don't even have a class, let alone multiple individual methods that have only a single reason to change.
And though it might make sense to start by breaking this autoloader method into smaller, individual methods, let's start from a higher level and begin thinking about an autoloader in terms of an interface. Then we'll drill down into creating a class (or classes).
Object-Oriented Analysis: Responsibilities
Recall from the previous tutorial that an interface is defined by the PHP manual as follows:
Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.
Given the code and the definitions above, let's think about what an autoloader needs to do from a more modular perspective. Specifically, let's break it down into points that represent what might be enough to change. No, we may not use all of these points, but this it's why it's called analysis. We'll work on the design later.
The code does the following:
- Validates we're working explicitly with our namespace.
- Splits the incoming class name into parts to determine if it's a class or an interface (so
$class_nameis a poor variable name). - Checks to see if we're working with an interface file.
- Checks to see if we're working with a class file.
- Checks to see if we're working with an interface.
- Based on the outcome of the above conditionals, generates a file name.
- Builds a file path based on the generated filename.
- If the file exists at the generated name, includes it.
- Otherwise, the code generates an error.
Thus, the above code does nine things—that is, it has at least nine reasons to change—before it's done completing its work.
This should go without saying, but this particular function is a perfect example that we can refactor to demonstrate object-oriented analysis, design, interfaces, and implementation.
And this raises a question: Where do we even begin?
Object-Oriented Analysis
At this point, it's fair to say that we can begin doing object-oriented analysis—that is, looking at what potential classes we may have and how they interact—given everything we've listed above. Remember, we also want the single responsibility principle to help guide us in our decision making.
At this point, we're not terribly concerned with how the classes will communicate with one another. Instead, we're more focused on creating classes that have a single reason to change.
With that said, I'm going to provide a sample set of classes that I think might work. Before going any further, look at what we've done and attempt to come up with your own list. Then we can compare notes.
A Word About Skills
Note that you may have a better idea than what's listed below, or you may take something away from what we've shared. Regardless, this is a learning exercise. We're attempting to improve our code, our organization, and ultimately become better programmers.
Our Potential Classes
Given what I've listed above, I've come up with the following classes:
- Autoloader. This is the main class that's responsible for ultimately including our class, our namespace, or our interface. We'll call this class. The rest are classes that will take care of necessary work that this one class needs to include the file.
- NamespaceValidator. This file will look at the incoming class, interface, or what have you, and will determine if it's valid. This will give us the deciding factor if we can proceed with the rest of our code our not.
- FileInvestigator. This class looks at the type of file that's being passed into the autoloader. It will determine if it's a class, an interface, or a namespace and return the fully-qualified path name to the file so that it may be included.
- FileRegistry. This will use the fully qualified file path ultimately returned from the other classes and will include it in the plugin.
And that's it. Now third-party classes in our plugin only need to know about the autoloader class, but the autoloader will need knowledge of another class, and other classes will need knowledge of yet other classes.
There are ways to handle this (using dependency injection containers, but that's beyond the scope of this project). But what we'll aim to do through our code is minimize how many classes know about one another.
Object-Oriented Design
At this point, different developers, firms, agencies, and teams will take a different approach to how they design the system on which they are working.
One of the most common ways to go about doing this is to use something called a UML diagram. Though it's useful, it's not something that's worth doing within the scope of this tutorial because it will require a whole other tutorial to explain all of the pieces.
So for the purposes of our tutorial, and since we're working with such a small amount of code, we'll try to stub out how each of the above classes may work before we implement them. This way, we'll get an idea of how we can organize our code.
Note that we won't be namespacing any of this code just yet, and none of this code should be implemented or tested against WordPress just yet. We'll get into that in the next tutorial.
Let's start with the Autoloader and work from there.
Autoloader
Remember, this class is responsible for including the necessary file. This is the file that will be registered with the spl_autoload_register function.
<?php
class Autoloader {
private $namespace_validator;
private $file_registry;
public function __construct() {
$this->namespace_validator = new NamespaceValidator();
$this->file_registry = new FileRegistry();
}
public function load( $filename ) {
if ( $this->namespace_validator->is_valid( $filename ) ) {
$this->file_registry->load( $filename );
}
}
}
Note that this class depends on the NamespaceValidator and the FileRegistry class. We'll see each of these in more detail in just a moment.
NamespaceValidator
This file will look at the incoming filename and will determine if it's valid. This is done by looking at the namespace in the filename.
<?php
class NamespaceValidator {
public function is_valid( $filename ) {
return ( 0 === strpos( $filename, 'Tutsplus_Namespace_Demo' ) );
}
}
If the file does in fact belong to our namespace, then we can assume it's safe to load our file.
FileInvestigator
This class is doing quite a bit of work, though part of it is done via very simple, very small helper methods. During the course of execution, it looks at the type of file that it's passed.
It then retrieves the fully-qualified filename for the type of file.
<?php
class FileInvestigator {
public function get_filetype( $filename ) {
$filepath = '';
for ( $i = 1; $i < count( $file_parts ); $i++ ) {
$current = strtolower( $file_parts[ $i ] );
$current = str_ireplace( '_', '-', $current );
$filepath = $this->get_file_name( $file_parts, $current, $i );
if ( count( $file_parts ) - 1 !== $i ) {
$filepath = trailingslashit( $filepath );
}
}
return $filepath;
}
private function get_file_name( $file_parts, $current, $i ) {
$filename = '';
if ( count( $file_parts ) - 1 === $i ) {
if ( $this->is_interface( $file_parts ) ) {
$filename = $this->get_interface_name( $file_parts );
} else {
$filename = $this->get_class_name( $current );
}
} else {
$filename = $this->get_namespace_name( $current );
}
return $filename;
}
private function is_interface( $file_parts ) {
return strpos( strtolower( $file_parts[ count( $file_parts ) - 1 ] ), 'interface' );
}
private function get_interface_name( $file_parts ) {
$interface_name = explode( '_', $file_parts[ count( $file_parts ) - 1 ] );
$interface_name = $interface_name[0];
return "interface-$interface_name.php";
}
private function get_class_name( $current ) {
return "class-$current.php";
}
private function get_namespace_name( $current ) {
return '/' . $current;
}
}
If there's a file that can be refactored a bit more, then this is it. After all, it attempts to determine if we're working with a class, an interface, or a class. A simple factory might be better suited to this.
When it comes time to implement our code, perhaps we'll refactor this further. Until then, this is a preliminary design that may work well enough.
FileRegistry
This will use the fully-qualified file path and include the file; otherwise, it will use the WordPress API to display an error message.
class FileRegistry {
private $investigator;
public function __construct() {
$this->investigator = new FileInvestigator();
}
public function load( $filepath ) {
$filepath = $this->investigator->get_filetype( $filepath );
$filepath = rtrim( plugin_dir_path( dirname( __FILE__ ) ), '/' ) . $filepath;
if ( file_exists( $filepath ) ) {
include_once( $filepath );
} else {
wp_die(
esc_html( 'The specified file does not exist.' )
);
}
}
}
Another alternative to using the WordPress API would be to throw a custom Exception message. That way, we'd be able to completely separate or decouple our code from WordPress.
Once again, this code is a carry-over from the initial autoloader. During implementation, we may change this, as well.
Conclusion
Alright, so we've looked at the existing code for our autoloader, and then we've stubbed out some potential code that we can use based on some object-oriented analysis and design.
Is the solution that we're working toward more maintainable than what we have? Absolutely. Is this going to work within the context of WordPress and our existing plugin? We won't know until we begin to hook this up into our plugin.
As previously mentioned, there are still some areas in which we could possibly refactor this code. If we hit these type of issues when implementing our code in the final version of our plugin, we'll take a look at doing exactly that.
Whatever the case, the code that we have now should be more readable (though we still have DocBlocks and some inline comments to introduce) and more maintainable and even more testable.
With all of that said, I hope that this has given you an idea as to how to take a long method and break it into more purpose-driven classes. Sure, having multiple classes might feel weird at first, but that doesn't mean it's a bad thing. Have more files (and thus classes) with less code than one file with a lot of code is better.
Embrace the counterintuitive nature of object-oriented programming in this regard. In the next tutorial, we're going to be returning to our plugin and will be working on implementing a variation of the code above. We'll likely be debugging some of it as well. After all, rarely do we get it right the first time
Until then, if you're interested in reading more about object-oriented programming in the context of WordPress, you can find all of my previous tutorials on my profile page. Feel free to follow my on my blog or follow me on Twitter where I frequently talk about both.
Resources
- Object-Oriented Autoloading in WordPress, Part 1
- Namespaces
- Autoloading
- Interfaces
- The WordPress Plugin API
- Single Responsibility Principle
Thursday, November 24, 2016
Exploring Devise, Part 2
Introduction
In the first part of the tutorial, we learned how to install Devise and set it up in our Rails application. In this part, we will look at how to integrate DeviseInvitable.
DeviseInvitable is an extension that works with Devise. With DeviseInvitable in your application, your users can invite their friends via emails. This is a great feature to include in your application if you are building a collaboration app.
Setting Up DeviseInvitable
Open your Gemfile and add the gem:
#Gemfile ... gem 'devise_invitable'
Run the command to install bundle install.
Run the generator command to add DeviseInvitable's configuration option to the Devise configuration file.
rails generate devise_invitable:install
You can see the new changes by checking out config/initializers/devise.rb with your text editor.
Next, let's add DeviseInvitable to our User model.
rails generate devise_invitable User
This will add the :invitable flag to your model, thus your User model will look like this:
#app/models/user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :invitable, :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
Running the above command also generated a migration file that looks like what I have below:
class DeviseInvitableAddToUsers < ActiveRecord::Migration
def up
change_table :users do |t|
t.string :invitation_token
t.datetime :invitation_created_at
t.datetime :invitation_sent_at
t.datetime :invitation_accepted_at
t.integer :invitation_limit
t.references :invited_by, polymorphic: true
t.integer :invitations_count, default: 0
t.index :invitations_count
t.index :invitation_token, unique: true # for invitable
t.index :invited_by_id
end
end
def down
change_table :users do |t|
t.remove_references :invited_by, polymorphic: true
t.remove :invitations_count, :invitation_limit, :invitation_sent_at, :invitation_accepted_at, :invitation_token, :invitation_created_at
end
end
end
Now migrate your database by running rake db:migrate.
Configuring the Controller for DeviseInvitable
DeviseInvitable is required to pass some parameters when sending an invite. For this to work, we need to whitelist the necessary parameter that will be used. Using your text editor, navigate to app/controllers/application_controller.rb and make yours look like what I have below:
#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
added_attrs = [:username, :email, :password, :password_confirmation, :remember_me]
devise_parameter_sanitizer.permit :sign_up, keys: added_attrs
devise_parameter_sanitizer.permit :account_update, keys: added_attrs
devise_parameter_sanitizer.permit :accept_invitation, keys: [:email]
end
end
From the above, you can see that :email has been whitelisted for DeviseInvitable.
Now let's see what we have via our console. On your terminal, run rails console and enter what you have below.
[1] pry(main)> User.invite!(:email => "johndoe@example.com")
It should produce the output that looks like what I have below, though there will be differences.
[2] pry(main)> User Load (78.3ms) SELECT "users".* FROM "users" WHERE "users"."email" = ? ORDER BY "users"."id" ASC LIMIT 1 [["email", "johndoe@example.com"]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."invitation_token" = ? ORDER BY "users"."id" ASC LIMIT 1 [["invitation_token", "658da470d5fcbb2275f30bc1fb66f5771b889cec2f1e56f536319d2fd1ef4a92"]]
(0.1ms) begin transaction
SQL (67.8ms) INSERT INTO "users" ("email", "encrypted_password", "invitation_token", "invitation_created_at", "invitation_sent_at", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["email", "johndoe@example.com"], ["encrypted_password", "$2a$11$0sLfqvfFDsebcmcQTUXzlOuqNIooL5z8niXeza8OUwNK3gZY/iRum"], ["invitation_token", "658da470d5fcbb2275f30bc1fb66f5771b889cec2f1e56f536319d2fd1ef4a92"], ["invitation_created_at", "2016-10-07 07:41:51.254047"], ["invitation_sent_at", "2016-10-07 07:41:51.254047"], ["created_at", "2016-10-07 07:41:51.255700"], ["updated_at", "2016-10-07 07:41:51.255700"]]
(220.5ms) commit transaction
Rendered /home/kinsomicrote/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/devise_invitable-1.7.0/app/views/devise/mailer/invitation_instructions.html.erb (2.5ms)
Rendered /home/kinsomicrote/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/devise_invitable-1.7.0/app/views/devise/mailer/invitation_instructions.text.erb (88.0ms)
Devise::Mailer#invitation_instructions: processed outbound mail in 247.1ms
Sent mail to johndoe@example.com (74.3ms)
Date: Fri, 07 Oct 2016 08:41:51 +0100
From: please-change-me-at-config-initializers-devise@example.com
Reply-To: please-change-me-at-config-initializers-devise@example.com
To: johndoe@example.com
Message-ID: <57f751bfce8d6_18022ac6c272b12840661@kinsomicrote-X553MA.mail>
Subject: Invitation instructions
Mime-Version: 1.0
Content-Type: multipart/alternative;
boundary="--==_mimepart_57f751bfcc725_18022ac6c272b12840524";
charset=UTF-8
Content-Transfer-Encoding: 7bit
----==_mimepart_57f751bfcc725_18022ac6c272b12840524
Content-Type: text/plain;
charset=UTF-8
Content-Transfer-Encoding: 7bit
Hello johndoe@example.com
Someone has invited you to http://localhost:3000/, you can accept it through the link below.
http://localhost:3000/users/invitation/accept?invitation_token=xmW9uRfyafptmeFMmFBy
If you don't want to accept the invitation, please ignore this email.
Your account won't be created until you access the link above and set your password.
----==_mimepart_57f751bfcc725_18022ac6c272b12840524
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
<p>Hello johndoe@example.com</p>
<p>Someone has invited you to http://localhost:3000/, you can accept it through the link below.</p>
<p><a href="http://localhost:3000/users/invitation/accept?invitation_token=xmW9uRfyafptmeFMmFBy">Accept invitation</a></p>
<p>If you don't want to accept the invitation, please ignore this email.<br />
Your account won't be created until you access the link above and set your password.</p>
----==_mimepart_57f751bfcc725_18022ac6c272b12840524--
=> #<User:0x00558d875fa798
id: 4,
email: "johndoe@example.com",
encrypted_password: "$2a$11$0sLfqvfFDsebcmcQTUXzlOuqNIooL5z8niXeza8OUwNK3gZY/iRum",
reset_password_token: nil,
reset_password_sent_at: nil,
remember_created_at: nil,
sign_in_count: 0,
current_sign_in_at: nil,
last_sign_in_at: nil,
current_sign_in_ip: nil,
last_sign_in_ip: nil,
created_at: Fri, 07 Oct 2016 07:41:51 UTC +00:00,
updated_at: Fri, 07 Oct 2016 07:41:51 UTC +00:00,
username: nil,
invitation_token: "658da470d5fcbb2275f30bc1fb66f5771b889cec2f1e56f536319d2fd1ef4a92",
invitation_created_at: Fri, 07 Oct 2016 07:41:51 UTC +00:00,
invitation_sent_at: Fri, 07 Oct 2016 07:41:51 UTC +00:00,
invitation_accepted_at: nil,
invitation_limit: nil,
invited_by_id: nil,
invited_by_type: nil,
invitations_count: 0>
[3] pry(main)>
That worked as planned.
You do not want our users to send invitations via the command line, so it is important we set up DeviseInvitable to work on the front end. Doing this is very simple; run the generator command to generate the views for DeviseInvitable.
rails generate devise_invitable:views users
You will also need to add a link somewhere in your application that points to the page for sending invites (app/views/users/invitations/new.html.erb).
For this application, you can go ahead and add the link to your navigation file. Here is how I did mine:
#app/views/shared/_navigation.html.erb
<nav class="navbar navbar-inverse">
<div class="container">
<div class="navbar-header">
<%= link_to 'Tutsplus Devise', root_path, class: 'navbar-brand' %>
</div>
<div id="navbar">
<ul class="nav navbar-nav">
<li><%= link_to 'Home', root_path %></li>
</ul>
<ul class="nav navbar-nav pull-right">
<% if user_signed_in? %>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<%= current_user.username %>
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li><%= link_to 'Invite', new_user_invitation_path %></li>
<li><%= link_to 'Profile', edit_user_registration_path %></li>
<li><%= link_to 'Log out', destroy_user_session_path, method: :delete %></li>
</ul>
</li>
<% else %>
<li><%= link_to 'Log In', new_user_session_path %></li>
<li><%= link_to 'Sign Up', new_user_registration_path %></li>
<% end %>
</ul>
</div>
</div>
</nav>
To see the routes made available by DeviseInvitable, run the command rake routes | invit. Here is what the output will look like.
cancel_user_registration GET /users/cancel(.:format) devise_invitable/registrations#cancel
user_registration POST /users(.:format) devise_invitable/registrations#create
new_user_registration GET /users/sign_up(.:format) devise_invitable/registrations#new
edit_user_registration GET /users/edit(.:format) devise_invitable/registrations#edit
PATCH /users(.:format) devise_invitable/registrations#update
PUT /users(.:format) devise_invitable/registrations#update
DELETE /users(.:format) devise_invitable/registrations#destroy
accept_user_invitation GET /users/invitation/accept(.:format) devise/invitations#edit
remove_user_invitation GET /users/invitation/remove(.:format) devise/invitations#destroy
user_invitation POST /users/invitation(.:format) devise/invitations#create
new_user_invitation GET /users/invitation/new(.:format) devise/invitations#new
PATCH /users/invitation(.:format) devise/invitations#update
PUT /users/invitation(.:format) devise/invitations#update
Let us see what we have at this moment. Run the command to start your server; rails server.
Point your browser to http://localhost:3000/users/invitation/new. Enter an email address in the form shown, and click on the button. That should work! If you go to the logs of your server, you should see an output that was created when you sent the invite. In the output, you will see a link to accept the invite.
You will agree with me that it will be better if you can view the email sent in your browser. Let us see how to make that work.
Integrating Letter_Opener
Letter Opener allows you preview emails in your default browser. With it, you do not have to set up a mail delivery system while working in the development environment.
Open your Gemfile and add the gem below:
gem 'letter_opener'
Run bundle install.
Using your text editor, navigate to config/environments/development.rb and add the line below.
#config/environments/development.rb ... config.action_mailer.delivery_method = :letter_opener end
Restart your rails server. Now point your browser to http://localhost:3000/users/invitation/new. Fill and submit the form displayed. This time, a new page pops up containing the invite email.
Change Default Sign In and Sign Out Routes
By default, the sign_in and sign_out routes when using Devise look like this:
sign_in: http://localhost:3000/users/sign_in
sign_out: http://localhost:3000/users/sign_out
To change it, go to config/routes.rb and add the following:
#config/routes.rb
as :user do
get 'signin' => 'devise/sessions#new'
post 'signin' => 'devise/sessions#create'
delete 'signout' => 'devise/sessions#destroy'
end
You can point your browser to http://localhost:3000/signin.
Conclusion
Now you know how to make use of DeviseInvitable. You also learned about the gem letter_opener. There are lots of things you can do with Devise, so check out the Wiki to learn more. Thanks for staying with me.
Wednesday, November 23, 2016
Tuesday, November 22, 2016
Monday, November 21, 2016
How to Perform Live Without Risking Your Hearing or Going Deaf
Live performance is often a loud experience, meaning musicians face an increased risk of hearing loss. In this tutorial I'll explain what hearing loss is, how it affects your hearing and ways to minimise the risk.
Noise-Induced Hearing Loss
Caused by sudden impulse sounds—such as explosions, or continuous high volume levels—such as rock concerts, this refers to hearing loss that is either temporary or permanent. Such hearing loss can be partial or total and may affect one ear or both.
How Hearing Works
Part of your inner ear is a fluid-filled structure called the cochlea, containing a membrane that sports thousands of tiny hairs that sway when the fluid moves. For an analogy, picture a wheat field in the wind.
This causes a chemical release, generating an electrical impulse along the auditory nerve to the brain where it’s interpreted as sound.
Tinnitus
Over-stimulation causes erratic or continuous vibration of these hairs. This is tinnitus, the ringing in the ears familiar to anyone who’s been to a fireworks display.
If you’re lucky, it lasts a few hours; if you’re not, it’s permanent.
The hairs can even die, causing partial or total hearing loss. Whilst some animals can regenerate these, humans can’t.
What to Listen For
There are three areas of concern:
- Sound Pressure Level
- Exposure Length
- Frequency
1. Sound Pressure Level
This is the force that sound exerts on a perpendicular surface. Put simply, it’s how much sound our ears are exposed to in any given moment. Measured in decibels, or dB, the higher the number the louder the sound.
Hearing loss is unlikely below 85dB, but increasingly likely at or above it. For reference:
- 60dB is normal conversation
- 85dB is heavy city traffic
- 105dB is maximum volume of an MP3 player
- 120dB is the sound of sirens
2. Exposure Length
The longer you spend in a loud environment then the greater your chance of hearing loss.
For example, club-goers are advised to take regular breaks. As well as preventing over-heating and dehydration, it gives your ears some respite from the loud music.
3. Frequency
Some frequencies can be more harmful than others in that damage occurs sooner and at lower decibel levels.
Whilst science is divided, it’s been recognised since the 19th century that sounds around 4kHz tend to be more harmful. It’s not an absolute, as similar effects have been noted from 3–8kHz, and it depends per person. However, the regions around 4kHz can be uncomfortable at best. You'll be familiar with that awful noise when a bus brakes harshly. That's 4kHz.
As a musician, you’ll experience 4kHz every time cymbals are struck. Since you can’t ban their usage you'll need to find ways to mitigate the sound.
Best Defence
There are practical ways to defend your ears. I’ll be talking from a guitarist’s perspective—because I am one—but this is applicable in a number of circumstances.
Reduce the Volume
Remember, the louder and longer the exposure, to the music, the greater the risk. If you’re playing loudly because of the drummer, tactfully ask them to ease up on their John Bonham impression. If that doesn’t work…
Distance
If possible set up as far from the drums as you can. Remember, damage occurs due to impulse sounds—drums, and frequencies around 4kHz—cymbals.
Not only will this help, you’ll play more quietly because you’re no longer competing. Your ears will thank you, as will the band.
Frequency Fights
I was once put next a keyboard player at a rehearsal. Immediately we realised this wouldn’t work; our instruments occupied similar frequencies, so we struggled to hear ourselves.
Instinct is to play louder and that annoys everyone. It also ncreases the risk of hearing loss.
There are two solutions:
- Stand somewhere else—see Distance
- Learn to EQ yourself. If you recognise where the instrument’s strongest frequencies are, reduce the weaker ones. You’ll hear, and be heard, more clearly plus your overall volume level will be lower
Size Matters
Playing at stadium volumes is fine if you actually play stadiums, but literally deafening if you’re in a rehearsal room.
The smaller the room, the quieter you should be.
Equipment
Unless you’re playing an acoustic gig, to a hushed crowd, you should wear either ear plugs or in-ear monitors.
Earplugs
Covering your ears—such as wearing ear defenders—is effective, but hardly practical. Thus, there are a number of solutions that prolong the safe period of exposure before loss occurs.
Plugs that just block the ears, such as foam, are cheap with a pack of 20 pairs from pharmacies are under £7. Your hearing, however, is now muffled, so you’ll played louder and that defeats the whole exercise.
Specialised plugs attenuate certain frequencies that means you’ll still hear to a useful extent and harmful exposure times are reduced. For years I’ve used Alpine Music Safe Pro plugs. They’re discreet, come in a small carry case and you can choose the level of attenuation up to 25dB. Prices start around £15.
I’ve recently tried Isolate from Flare Audio. These are metal plugs designed to block the ear canal and hearing occurs via bone conductivity. Volume reduction is impressive, and frequency response is quite natural. They take getting used to, but my hearing hasn’t suffered during exposure. Prices start from £25.
In-Ear Monitors
These are discreet headphones that plug your ears. Sound engineers love them, as they reduce the need for onstage speakers. Provided with a good mix, you should hear everything clearly.
However, they’ve three major drawbacks:
- They’re not cheap. Plugs aside, you need a separate receiver and transmitter. The very cheapest start above £100
- Batteries and electronics; if any fail, you won’t hear a thing
- If the environment’s loud, you’ll turn your monitors up. As they’re in your ears, the risk of hearing loss increases, defeating the object
Personally, I don’t use them; I prefer earplugs and achieving a good onstage mix
Conclusion
Hearing is precious, so protect it by:
- Avoiding excessive volume, long exposures, and harmful frequencies
- Set overall volume to the size of the room
- Move away from loud sounds
- EQ increases clarity without boosting overall volume
- Don’t compete with high volumes or similar sounds
- Use flat-frequency ear plugs
How to Handle Routing in React
In one of my earlier tutorials, we saw how to get started with React and JSX. In this tutorial, we'll see how to get started with setting up and creating a React app. We'll focus on how to handle routing in a React app using react-router.
Getting Started
Let's start by initiating our project using Node Package Manager (npm).
mkdir reactRoutingApp cd reactRoutingApp npm init
Install the required react and react-dom libraries in the project.
npm install react react-dom --save
We'll be using webpack module bundler for this project. Install webpack and webpack development server.
npm install webpack webpack-dev-server --save-dev
We'll make use of Babel to convert JSX syntax to JavaScript. Install the following babel package in our project.
npm install --save-dev babel-core babel-loader babel-preset-react babel-preset-es2015
webpack-dev-server requires a config file where we'll define the entry file, output file, and the babel loader. Here is how our webpack.config.js file will look:
module.exports = {
entry: './app.js',
module: {
loaders: [
{
exclude: /node_modules/,
loader: 'babel-loader?presets[]=es2015&presets[]=react'
}
]
},
output: {
filename: 'bundle.js'
}
};
Next we'll create app.html where the React app will get rendered.
<html>
<head>
<title>TutsPlus - React Routing Basic</title>
</head>
<body>
<div id="app"></div>
<script src="bundle.js"></script>
</body>
</html>
Let's create the entry point file app.js for our React application.
import React from 'react';
import {render} from 'react-dom';
const App = () => {
return (
<h2>{'TutsPlus - Welcome to React Routing Basic!'}</h2>
);
};
render(
<App />,
document.getElementById('app')
);
As seen in the above code, we have imported react and react-dom. We created a stateless component called App which returns a title. The render function renders the component inside the app element in the app.html page.
Let's start the webpack server, and the app should be running and displaying the message from the component.
webpack-dev-server
Point your browser to http://localhost:8080/app.html and you should have the app running.
Creating React Views
Now we are up and running with our React application. Let's start by creating a couple of views for our React routing application. Just to keep it simple, we'll create all the components inside the same app.js file.
Let's create a main component called navigation in the app.js.
const Navigation = () => {
return (
<section>
<App />
<ul>
<li>{'Home'}</li>
<li>{'Contact'}</li>
<li>{'About'}</li>
</ul>
</section>
);
};
In the above Navigation component, we have the app title and a newly created menu for navigation to different screens of the app. The component is quite simple, with basic HTML code. Let's go ahead and create screens for Contact and About.
const About = () => {
return (
<section>
<h2>{'Welcome to About!'}</h2>
</section>
);
};
const Contact = () => {
return (
<section>
<h2>{'Welcome to Contact!'}</h2>
</section>
);
};
We just created a component to render the About and Contact screens.
Connecting Views Using react-router
In order to connect different views we'll make use of react-router. Install the react-router using npm.
npm install react-router --save
Import the required library from react-router in app.js.
import {Link, Route, Router} from 'react-router';
Instead of specifying which component to render, we'll define different routes for our application. For that we'll make use of react-router.
Let's define the routes for the Home screen, Contact screen, and About screen.
render(
<Router>
<Route
component={Navigation}
path="/"
/>
<Route
component={About}
path="/about"
/>
<Route
component={Contact}
path="/contact"
/>
</Router>,
document.getElementById('app')
);
When the user visits the / route, the Navigation component gets rendered, on visiting /about the About component gets rendered, and /contact renders the Contact component.
Modify the About and Contact screens to include a link back to the home screen. For linking screens, we'll use Link, which works in a similar way to the HTML anchor tag.
const About = () => {
return (
<section>
<h2>{'Welcome to About!'}</h2>
<Link to="/">{'Back to Home'}</Link>
</section>
);
};
const Contact = () => {
return (
<section>
<h2>{'Welcome to Contact!'}</h2>
<Link to="/">{'Back to Home'}</Link>
</section>
);
};
Modify the Navigation component to include the link to the other screens from the home screen.
const Navigation = () => {
return (
<section>
<App />
<ul>
<li>{'Home'}</li>
<li>
<Link to="/contact">{'Contact'}</Link>
</li>
<li>
<Link to="/about">{'About'}</Link>
</li>
</ul>
</section>
);
};
Save the changes and restart the webpack server.
webpack-dev-server
Point your browser to http://localhost:8080/app.html, and you should have the app running with basic routing implemented.
Wrapping It Up
In this tutorial, we saw how to get started with creating a React app and connecting different components together using react-router. We learnt how to define different routes and link them together using react-router.
Have you tried using react-router or any other routing library? Do let us know your thoughts in the comments below.
Source code from this tutorial is available on GitHub.
Sunday, November 20, 2016
Friday, November 18, 2016
Object-Oriented Autoloading in WordPress, Part 1
I recently wrapped up a series in which I covered namespaces and autoloading in WordPress. If you're not familiar with either of the above terms, then I recommend checking out the series.
The gist of what you can expect to learn is as follows:
In this series, we're going to take a look at exactly what PHP namespaces are, why they are beneficial, and how to use them. Then we're going to take a look at how to use autoloaders to automatically load the files that we need without having to manually load them in our code.
While working on the series, specifically that of the autoloader, I couldn't help but recognize a number of code smells that were being introduced as I was sharing the code with you.
This isn't to say the autoloader is bad or that it doesn't work. If you've downloaded the plugin, run it, or followed along and written your own autoloader, then you know that it does in fact work.
But in a series that focuses on namespaces—something that's part and parcel of object-oriented programming—I couldn't help but feel uncomfortable leaving the autoloader in its final state at the end of the series.
Don't misread me: I still stand by the series, what was covered, and the end result of what we produced. But from an object-oriented standpoint, there's more work that can be done. So in this follow-up series, we're going to be revisiting the concept of autoloaders from the perspective of object-oriented programming.
Specifically, we're going to talk about the concept of:
- interfaces
- interface implementation
- the single-responsibility principle
- and other principles and ideas that are core to object-oriented programming
It is my hope that by the time we complete this series, we will not only have refactored our autoloader into something that's more maintainable and easier to read, but that it also adheres to greater object-oriented practices.
With that said, let's get started.
Getting Started
As with nearly every post I write, I like to try to do two things:
- Define a roadmap of where we're going.
- Give you everything you need to know to get your machine up and running.
Before we jump into writing any code, let's do that now.
Our Roadmap
Over the next two posts, we're going to take a look at some object-oriented concepts that are going to allow us to improve on the plugin that we built in the previous series.
If you don't have a copy of that plugin, then you can download a copy of it; however, I'll be sharing complete code examples, comments, and explanations throughout each tutorial.
The series is going to assume you know nothing about any of the concepts that we'll be discussing so we'll be starting from the ground up. All you need is to have enough software on your machine to get a copy of WordPress up and running, and an editor in which you can edit code.
What You Need
To get started, you're going to need the following tools:
- A local development environment that includes at least PHP 5.6.20, the Apache web server, and a MySQL database server. MAMP 4 is perfect for this.
- A directory out of which WordPress 4.6.1 is being hosted.
- A text editor or IDE of your choice that you're comfortable using for writing a plugin.
- A working knowledge of the WordPress Plugin API.
After you have all of that in place (and I know it seems like a lot, but it really doesn't take long to set up), you'll need to install a copy of the plugin linked above.
Once done, we're ready to start talking about interfaces and the single responsibility principle.
Interfaces Defined
Depending on your background in software, when you hear the word "interface," you may end up thinking of what the user actually sees on the screen. You know: A user interface.
But when it comes to object-oriented design, that's not what we're talking about at all. Instead, we're talking about a class interface. And this can usually be described as the class and the public methods it exposes for other classes to communicate with it.
Is there a more formal definition? Sure. Wikipedia offers one:
In computing, an interface is a shared boundary across which two separate components of a computer system exchange information.
This isn't that bad, actually. It's general enough to apply to nearly any programming language, and it's not so technical that we can't understand it.
Then again, we're working with PHP. So what does the PHP manual have to offer on the topic?
Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.
In my opinion, this is a really good definition. It's simple. It's language agnostic (to my knowledge), and it works well across most (if not all) object-oriented languages. The manual even goes on to say:
Interfaces are defined in the same way as a class, but with the interface keyword replacing the class keyword and without any of the methods having their contents defined.
All methods declared in an interface must be public; this is the nature of an interface.
These are two points that we must remember if we're going to be implementing our own interfaces, especially when it comes to this plugin. Namely, we need to remember the following:
- We define an interface much like we do a class, but we use the
interfacekeyword. - The methods that are defined in an interface have to the public (as opposed to being
protectedorprivate) because this is what guarantees the functionality other classes can access.
Before we go any further, what might an interface in a WordPress project look like? Here's an example from a project I've been working on:
<?php
/**
* Defines a common set of functions that any class responsible for loading
* stylesheets, JavaScript, or other assets should implement.
*/
interface Assets_Interface {
public function init();
public function enqueue();
}
The code above should be clear as to what purpose it serves, especially given the comment that sits above the interface.
As we all know, WordPress can register and enqueue two types of assets: stylesheets and JavaScript files.
Since both of these are assets, then it would stand to reason that when we create classes for stylesheet management or JavaScript management, we'd generalize it as an assets interface, right?
Furthermore, we know we want to initialize the file using an init method so that we can hook the specified enqueue function to the proper WordPress API function. Alternatively, there may be some other work you'd like to do, and if that's the case, then you may want to add another method signature to the interface.
Whatever the case may be, any class that implements this interface must provide functionality for the following methods. So what would a class that implements this interface look like?
Here's a very simple example of a class that adds stylesheets to the administration area of WordPress:
<?php
class CSS_Loader implements Assets_Interface {
/**
* Registers the 'enqueue' function with the proper WordPress hook for
* registering stylesheets.
*/
public function init() {
add_action(
'admin_enqueue_scripts',
array( $this, 'enqueue' )
);
}
/**
* Defines the functionality responsible for loading the file.
*/
public function enqueue() {
wp_enqueue_style(
'tutsplus-namespace-demo',
plugins_url( 'assets/css/admin.css', dirname( __FILE__ ) ),
array(),
filemtime( plugin_dir_path( dirname( __FILE__ ) ) . 'assets/css/admin.css' )
);
}
}
Now how this is instantiated and enforced via PHP is beyond the scope of this tutorial. We'll see it plenty when we begin refactoring our autoloader.
But the point I'm trying to show is that an interface defines the public methods a class must implement. It doesn't define the implementation, but it guarantees that a certain set of functions will exist and are publicly accessible to third-party classes.
The Single Responsibility Principle
One of the challenges of talking about the single responsibility principle is that it's often been misunderstood to mean something like:
A class (or function or routine) should do one and only one thing.
But that's a little misguided, isn't it? I mean even a simple for loop does more than one thing: It initializes a value, compares to values, and then iterates the value when the body of the loop is complete.
Instead, the principle states the following:
A class should have only one reason to change.
Because so many of us developers leverage Google to help us in our day-to-day work, I think it's important to understand the source of this idea. That is, this came from Uncle Bob Martin, as he's casually known, or Robert Martin, who has authored a number of top-shelf programming books.
The idea of a class having only one reason to change carries with it a whole host of implications, doesn't it? Here's one example that comes to mind from our autoloader as it stands today.
Let's review the code (and I know it's not a class, it's a function, but the principle is applicable):
<?php
/**
* Dynamically loads the class attempting to be instantiated elsewhere in the
* plugin.
*
* @package Tutsplus_Namespace_Demo\Inc
*/
spl_autoload_register( 'tutsplus_namespace_demo_autoload' );
/**
* Dynamically loads the class attempting to be instantiated elsewhere in the
* plugin by looking at the $class_name parameter being passed as an argument.
*
* The argument should be in the form: TutsPlus_Namespace_Demo\Namespace. The
* function will then break the fully-qualified class name into its pieces and
* will then build a file to the path based on the namespace.
*
* The namespaces in this plugin map to the paths in the directory structure.
*
* @param string $class_name The fully-qualified name of the class to load.
*/
function tutsplus_namespace_demo_autoload( $class_name ) {
// If the specified $class_name does not include our namespace, duck out.
if ( false === strpos( $class_name, 'Tutsplus_Namespace_Demo' ) ) {
return;
}
// Split the class name into an array to read the namespace and class.
$file_parts = explode( '\\', $class_name );
// Do a reverse loop through $file_parts to build the path to the file.
$namespace = '';
for ( $i = count( $file_parts ) - 1; $i > 0; $i-- ) {
// Read the current component of the file part.
$current = strtolower( $file_parts[ $i ] );
$current = str_ireplace( '_', '-', $current );
// If we're at the first entry, then we're at the filename.
if ( count( $file_parts ) - 1 === $i ) {
/* If 'interface' is contained in the parts of the file name, then
* define the $file_name differently so that it's properly loaded.
* Otherwise, just set the $file_name equal to that of the class
* filename structure.
*/
if ( strpos( strtolower( $file_parts[ count( $file_parts ) - 1 ] ), 'interface' ) ) {
// Grab the name of the interface from its qualified name.
$interface_name = explode( '_', $file_parts[ count( $file_parts ) - 1 ] );
$interface_name = $interface_name[0];
$file_name = "interface-$interface_name.php";
} else {
$file_name = "class-$current.php";
}
} else {
$namespace = '/' . $current . $namespace;
}
}
// Now build a path to the file using mapping to the file location.
$filepath = trailingslashit( dirname( dirname( __FILE__ ) ) . $namespace );
$filepath .= $file_name;
// If the file exists in the specified path, then include it.
if ( file_exists( $filepath ) ) {
include_once( $filepath );
} else {
wp_die(
esc_html( "The file attempting to be loaded at $filepath does not exist." )
);
}
}
There is a lot of stuff happening within this function. Just looking at it from a high level, we can see that it's doing the following:
- It determines if PHP is trying to invoked the code in this function.
- The function determines if we're loading an interface or a class.
- The autoloader then tries to include the file or it throws an error.
If a class is supposed to only have one reason to change, there are three reasons above (and that's just at a high level) at which this single function could change. Furthermore, the code could be clearer, as well.
I'm not one to shy away from code comments, but there's a lot of explanation happening in the code above. And it's fine when you're just getting started writing an autoloader, but when you're headed into more advanced territory such as we are, then that won't hold up to more rigorous architectures.
Bringing the Two Together
This is where interfaces and the single responsibility principle can come to work hand in hand.
Just as an interface provides a set of function signatures (or a contract) for what its implementers will provide, it can ensure that any class implementing that interface adheres strictly to what it defines.
But this raises an interesting question: Should we have multiple interfaces? And the answer is that it depends on the nature of the solution that you're trying to create.
In our case, I think it makes sense.
After all, we're looking to examine an incoming class name and determine if it's a interface or a class, or if it deserves to throw an error. Furthermore, we're looking to ensure that the proper file is included with the rest of the system.
But that's beyond the topic of this particular tutorial and one we'll have to explore in more depth when it comes time to write more code.
Conclusion
At this point, we've covered the necessary concepts so that we can begin refactoring our autoloader. That is, we'll be introducing an interface, making sure our code adheres to it, and then we'll make sure our class (or classes) and their respective methods adhere to the single responsibility principle.
Furthermore, we'll make sure that it continues to function well within the context of the plugin, it's properly documented, and that it follows the WordPress Coding Standards.
In the meantime, if you're interested in reading more about object-oriented programming in the context of WordPress, you can find all of my previous tutorials on my profile page. Feel free to follow me on my blog or follow me on Twitter where I frequently talk about both.
As always, if you're looking for other utilities to help you build out your growing set of tools for WordPress or for example code to study and become more well versed in WordPress, don't forget to see what we have available in Envato Market.
With that said, the next tutorial in the series is going to be far more practical. That is, we'll be writing code, refactoring existing code, and applying everything we've learned in this tutorial. Until then, don't hesitate to leave any feedback in the comments.
Resources
- Namespace and Autoloader Plugin
- Namespaces
- Autoloading
- Interfaces
- The WordPress Plugin API
- MAMP 4
- Single Responsibility Principle
Thursday, November 17, 2016
Wednesday, November 16, 2016
Tuesday, November 15, 2016
Monday, November 14, 2016
Let's Go: Golang Code Organization
Go is a special language among modern languages. It is very opinionated. For example, there is one true formatting. Go will tell you how to space your code and where to put your curly braces. But it goes much deeper than that.
Go will also tell you how to capitalize your functions and variables to make them public or private. It will dictate the directory structure of your code. This may come as a surprise for developers coming to Go from more liberal programming languages.
In this article, I'll explore some of Go's restrictions, discuss their merits, and suggest options for common situations.
Project Euler
When I started learning Go, I created a solution to Problem #6 and just put it in a sub-directory alongside solutions to other problems in other languages. See Project Euler.
The issue is that Go doesn't want you to just scatter Go files randomly all over the place. I later realized that while it works in very simple cases where you don't import other packages, it is not proper.
Dependencies
Every non-trivial program is composed of multiple files or modules or components or classes. I'll just use "file" as a general term. They are often grouped in libraries or packages or assemblies. I'll just use "package" as a general term. The code you write depends on code in other files and packages.
You need to tell your code how to find those packages and files in order to use their functionality. Each language has its own term: import, include, require. I'll just use "import" as a general term.
Some languages (or language specific tools) also allow you to install dependencies from a remote package repository and install them into a standard local location you can import from.
In most common programming languages, you have a lot of freedom. In C/C++, you tell the compiler/linker where the files and static libraries are (using command-line switches or environment variables like INCLUDE_DIR). In Python, you can install packages from PyPI using setup.py or with pip from PyPI and remote source control repositories. You then import based on the sys.path package search path.
The Go Way
Go, as always, is more prescriptive. It may offend your creativity that you don't get as much say about where to place things, but at the end of the day it doesn't really matter, and there is enough flexibility to accommodate various situations.
Go requires that you put your code in a workspace. A workspace is just a directory with three sub-directories: src, pkg, and bin. It is recommended that you keep all your projects under a single workspace. This way they can depend on each other and share common third-party packages.
Note: I currently work on Windows and use PowerShell for many of the interactive examples. For the following section, I wanted to show the directory structure of my workspace using the tree command. Windows has its own tree.exe command, but it is very limited (no levels). There is allegedly a full-fledged tree command for Windows here.
But the site was unreachable. I ended up firing a Docker container running Ubuntu, mounting my Go workspace as /docs/Go, and using the Linux tree command to show it. So don't be confused if you see a Linux environment showing Windows directories and files with .exe suffixes.
Here is my current Go workspace. The bin directory contains various Go commands/tools, and the delve debugger. The pkg dir has a sub-directory with the platform (Win 64) that contains the packages organized by their origin (github.com, golang.com, etc.). The src directory has similar sub-directories for the origin repository or website (github.com, golang.org, etc.).
root@67bd4824f9d5:/docs/Go# tree -n -L 3
|-- bin
| |-- dlv.exe
| |-- go-outline.exe
| |-- go-symbols.exe
| |-- gocode.exe
| |-- godef.exe
| |-- golint.exe
| |-- gometalinter.exe
| |-- gopkgs.exe
| |-- gorename.exe
| |-- goreturns.exe
| `-- guru.exe
|-- pkg
| `-- windows_amd64
| |-- github.com
| |-- golang.org
| |-- gopkg.in
| `-- sourcegraph.com
`-- src
|-- github.com
| |-- alecthomas
| |-- derekparker
| |-- go-web-crawler
| |-- golang
| |-- google
| |-- lukehoban
| |-- multi-git
| |-- newhook
| |-- nsf
| |-- rogpeppe
| |-- tpng
| `-- x
|-- golang.org
| `-- x
|-- gopkg.in
| `-- alecthomas
`-- sourcegraph.com
`-- sqs
27 directories, 11 files
Let's take a look inside one of the source projects I created under src: the go-web-crawler. It is pretty simple here: just a flat list of Go files, a license, and a README file.
root@67bd4824f9d5:/docs/Go# tree src/http://ift.tt/2fRNh06 -n src/http://ift.tt/2fRNh06 |-- LICENSE |-- README.md |-- channel_crawl.go |-- main.go `-- sync_map_crawl.go 0 directories, 5 files
GOROOT and GOPATH
Two environment variables control your destiny in the land of Go. GOROOT is where the Go installation is:
09:21:26 C:\Users\the_g\Documents\Go> ls Env:\GOROOT
Name Value
---- -----
GOROOT C:\Go\
09:21:35 C:\Users\the_g\Documents\Go> ls c:\go
Directory: C:\go
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 8/16/2016 10:38 AM api
d----- 8/16/2016 10:38 AM bin
d----- 8/16/2016 10:38 AM blog
d----- 8/16/2016 10:38 AM doc
d----- 8/16/2016 10:38 AM lib
d----- 8/16/2016 10:38 AM misc
d----- 8/16/2016 10:38 AM pkg
d----- 8/16/2016 10:38 AM src
d----- 8/16/2016 10:38 AM test
-a---- 8/16/2016 1:48 PM 29041 AUTHORS
-a---- 8/16/2016 1:48 PM 1168 CONTRIBUT
-a---- 8/16/2016 1:48 PM 40192 CONTRIBUT
-a---- 8/16/2016 1:48 PM 1150 favicon.i
-a---- 8/16/2016 1:48 PM 1479 LICENSE
-a---- 8/16/2016 1:48 PM 1303 PATENTS
-a---- 8/16/2016 1:48 PM 1638 README.md
-a---- 8/16/2016 1:48 PM 26 robots.tx
-a---- 8/16/2016 1:48 PM 5 VERSION
Note that the Go root directory looks like a superset of a workspace with the src, bin, and pkg directories.
GOPATH points to your workspace. That's how Go finds your code.
09:21:53 C:\Users\the_g\Documents\Go> ls Env:\GOPATH Name Value ---- ----- GOPATH c:\Users\the_g\Documents\Go
There are a bunch of other Go related environment variables, many of which you were required to set in the past (e.g. GOOS and GOARCH). Now, they are optional, and you should not mess with them unless you really need to (e.g. when cross-compiling). To see all the Go environment variables, type: go env.
09:51:10 C:\Users\the_g> go env set GOARCH=amd64 set GOBIN= set GOEXE=.exe set GOHOSTARCH=amd64 set GOHOSTOS=windows set GOOS=windows set GOPATH=c:\Users\the_g\Documents\Go set GORACE= set GOROOT=C:\Go set GOTOOLDIR=C:\Go\pkg\tool\windows_amd64 set CC=gcc set GOGCCFLAGS=-m64 -mthreads -fmessage-length=0 set CXX=g++ set CGO_ENABLED=1
Installs and Imports
When you create a Go program or a library, you can install it. Programs go to your workspace's bin directory, and libraries go to the workspace's pkg directory. On Windows, I discovered that your %GOPATH%/bin is not in the %PATH% directory, so Windows couldn't find my executable. I added it to the Windows PATH and everything worked. Here is how to check in PowerShell that your PATH contains your workspace bin directory:
10:56:19 C:\Users\the_g> $env:path.split(";") | grep go
C:\Go\bin
c:\Users\the_g\Documents\Go\bin
Let's see all that in action.
If I go to my go-web-crawler directory and type go install then go-web-crawler.exe is created in c:\Users\the_g\Documents\Go\bin:
11:09:18 C:\Users\the_g> ls $env:GOPATH/bin
Directory: C:\Users\the_g\Documents\Go\bin
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 8/15/2016 11:05 AM 15891456 dlv.exe
-a---- 8/15/2016 10:08 AM 3972608 go-outline.exe
-a---- 8/15/2016 10:10 AM 4502528 go-symbols.exe
-a---- 9/18/2016 10:14 AM 1849856 go-web-crawler.exe
-a---- 8/15/2016 10:08 AM 12097024 gocode.exe
-a---- 8/15/2016 10:17 AM 6642688 godef.exe
-a---- 8/15/2016 9:32 AM 6625792 golint.exe
-a---- 8/15/2016 10:14 AM 6352896 gometalinter.exe
-a---- 8/15/2016 10:10 AM 2738688 gopkgs.exe
-a---- 8/15/2016 10:10 AM 6961152 gorename.exe
-a---- 8/15/2016 10:09 AM 7291904 goreturns.exe
-a---- 8/15/2016 10:11 AM 9722368 guru.exe
I can now run it from my Go web crawler from anywhere.
11:10:32 C:\Users\the_g> go-web-crawler.exe found: http://golang.org/ "The Go Programming Language" found: http://golang.org/cmd/ "" not found: http://golang.org/cmd/ found: http://golang.org/pkg/ "Packages" found: http://ift.tt/SYJMCr "Package os" found: http://ift.tt/1i4Ho7x "Package fmt" found: http://golang.org/ "The Go Programming Language"
Multiple Go Environments
That's all fine, but sometimes life is not so simple. You may want to have multiple separate workspaces. What's more, you may want to have multiple installations of Go (e.g. different versions) and multiple workspaces for each one. You can do this by dynamically setting GOPATH for changing the workspace and setting GOROOT for changing the active Go installation.
There are various open-source projects for vendoring, package management, and virtual environments. For some reason, most don't support Windows. I'm not sure why such tools have to be platform-specific. I may write a cross-platform Go environment manager myself one of these days.
Conclusion
Go is all about eliminating incidental complexity. Sometimes it comes off as very strict and prescriptive. But if you get into the mindset of the Go designers, you start to understand that avoiding, forbidding or mandating certain things really makes everything simpler.
Sunday, November 13, 2016
Friday, November 11, 2016
Using Namespaces and Autoloading in WordPress Plugins, Part 3
In this tutorial, we're going to take a break from writing code and look at what PHP namespaces and autoloaders are, how they work, and why they are beneficial. Then we'll prepare to wrap up this series by implementing them in code.
If you're not caught up with everything we've covered in the series by this point, I recommend going back and reviewing what we've covered thus far. At the very least, review the previous article as it's going to lay the foundation for what we'll be talking about in the next two articles.
Now that you're caught up, you're aware of the plugin we've been working on, what it does, and how it works. Further, you should have a local development environment set up that allows you to work with the source code. If not, here's a quick rundown of everything that you need:
- A local development environment that includes PHP 5.6.20, the Apache web server, and a MySQL database server.
- A directory out of which WordPress 4.6 is being hosted.
- A text editor or IDE of your choice that you're comfortable using for writing a plugin.
- A working knowledge of the WordPress Plugin API.
Assuming you have all of that installed, set up, and ready to go along with the latest version of the plugin, then we're ready to resume our discussion on namespaces, autoloading, and WordPress plugins.
On Namespaces and Autoloading
For those who have worked in other modern programming languages, you may be familiar with the concept of namespaces. But even if you've worked with PHP, it's not likely that you've seen them much, at least in the context of WordPress.
For those of you who haven't heard of them or who have heard of them but haven't used them, that's what this particular article is all about. Specifically, we're going to talk about namespaces and autoloading and then, in the next tutorial, we'll see how it all fits together.
That is, we're going to take the work that we've done with our plugin thus far and then update it so that it uses namespaces and autoloading. This will give you a practical understanding of the concepts as well as a few new tools to add to your development repertoire for when you work on your next project.
What Are Namespaces?
As with most of my tutorials, I like to give the formal definition and then break it down into more conversational terms. The PHP manual defines namespaces like this:
In the broadest definition namespaces are a way of encapsulating items.
That doesn't necessarily help us much, does it? One could argue that classes do the same thing permitting attributes and functions can both be generalized as items. But the manual goes on:
PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants.
That's a bit clearer, right? This means that when we have a group of related classes, we may be grouping them together in the same directory or similar directories on the filesystem, but there's no way to know that by looking at the code.
Namespaces give us the ability to do that.
Think of it this way: Imagine that you have a set of functionality related to working with CSVs.
- Perhaps you have a class that's responsible for reading a CSV file, parsing the contents, and reading the contents into an array.
- Then you have a class that's responsible for taking that array and writing data to the database based on what the array contains.
- After that, there's a class responsible for reading those options whenever a third-party object or another area in the code needs to read the data that was read, parsed, and saved earlier in the project's execution.
All of this functionality should span several classes. Depending on how object-oriented code your solution is, you may also have a set of interfaces that your classes implement. Furthermore, the classes may be organized in a /csv directory but broken down even further into their own subdirectories.
/read/write
Maybe you would opt to organize the structure a bit differently, but to keep the discussion as simple as possible, I thought this would make sense. So perhaps the class interface(s) would reside in the root of the /csv directory, the reader would reside in the /read directory, and the classes responsible for writing the data to the database would reside in the /write directory.
Nothing I've said thus far is out of the ordinary in terms of how we may organize our files. But this is where namespaces come into play.
Specifically, what if we were able to organize our classes so they also mapped to their physical location in the filesystem?
Think of it this way: Let's say your plugin is called Acme CSV, and the classes above are all organized in their directories and subdirectories and so on. What might the namespaces look like for these classes, and how would they be declared within the project?
Take a look at what we'll call the Parser class. This class is located in /csv/read.
<?php
namespace Acme_CSV\CSV\Read;
class Parser {
// Class Implementation
}
And then let's say we have our class that writes data to the database:
<?php
namespace Acme_CSV\CSV\Write;
class Serializer {
// Class Implementation
}
Finally, let's see what the namespace for the class is like that reads data from the database:
<?php
namespace Acme_CSV\CSV\Read;
class Reader {
// Class Implementation
}
Nothing terribly complicated, right? Though the standard above isn't how you have to organize your files, I like to try to map my classes to their location on disk. It makes it easier to refer to them in future work.
At this point, there's really nothing much more to see beyond declaring a type of organization of your classes at the top of their files. But when you begin to incorporate autoloading, this changes.
A Word on Packages and Subpackages
Before we talk about autoloading, though, I want to have a short digression on the @package and @subpackage tags that we're often so used to seeing in file comments.
For example, you've likely seen something like this with respect to our code above:
<?php /** * This is the file comment for the Serializer class. * * @package Acme_CSV * @subpackage Write */
But when you refer to the phpDocumentor documentation, you'll see the following about @subpackage:
This tag is considered deprecated and may be removed in a future version of phpDocumentor. It is recommended to use the @package tag’s ability to provide multiple levels.
So @subpackage is being deprecated, meaning that we likely shouldn't bother using it anymore. What about the @package tag?
The @package tag is used to categorize Structural Elements into logical subdivisions.
The support for multiple-level nesting now resides solely in that tag. Good to know, right? This means the code we see above could be written something like this:
<?php /** * This is the file comment for the Serializer class. * * @package Acme_CSV\Write */
Sure, it's a simple example, but it makes its point. I mention this because @subpackage is yet another tag that we often see in WordPress-based PHP that we need to avoid using if we want to begin adopting newer standards.
What Is Autoloading?
With that said, let's come back to the primary topics at hand. Since we've covered namespaces, let's look at autoloading. According to the PHP manual:
Many developers writing object-oriented applications create one PHP source file per class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).
This couldn't be stated any better, could it? Still, it doesn't really explain what autoloading is. It just explains the problem it can solve.
In PHP 5, this is no longer necessary ... [it supports loading] classes and interfaces to be automatically loaded if they are currently not defined.
Sounds fantastic, right? But there's a caveat, and we're going to explore it in detail in the next tutorial. But until then, here it is: To gain this functionality, we have to implement a function that knows where to look for files to load and how to parse the directory structure of those files.
It sounds tedious, and it some cases it might be, but if you have a consistent way of organizing your work, your autoloading code can be portable. That is, you can take the function you write, drop it into any PHP-based project, and be ready to go all the same.
But this specific tutorial isn't about writing code. It's about covering the idea behind the concepts of the code that we'll be implementing in the next tutorial.
Why Is Any of This Relevant?
Depending on who you ask, you may view namespaces and autoloading as new to PHP. For some, this is true. For others, they've been working with these two concepts for a while now.
One of the things about WordPress that can hold it back from adopting newer features of PHP is its commitment to backward compatibility. This isn't necessarily a good thing or a bad thing—it's an attribute of the application.
But because WordPress has a minimum version of PHP on which it runs, newer language features aren't always adopted. And when that minimum version is adopted, it takes WordPress-specific developers a little while to begin using these features in their code.
And that's not a bad thing. In short, the developers are keeping pace with the application at the pace at which it matures.
But as WordPress continues to move forward or you have control over the environment in which your project runs, you may be interested in adopting some of the features of the language you didn't previously know existed or you didn't previously know were available.
Namespaces and autoloading are two powerful features of the language that go a long way in making the code more readable, more organized, and even a bit more maintainable. So if you've yet to use them in any of your work in WordPress, especially if you're working with WordPress plugins, then I urge you to consider doing so.
Conclusion
Namespaces give us the ability to organize our code in a way that makes the logical grouping of related classes much easier. Furthermore, autoloading gives our code more readability by reducing the number of include, include_once, require, or require_once statements that we need to use.
This makes the source code that we're writing clearer in that it's focused solely on the logic for which it's responsible, without having to do anything like import files, handle various directory structures, and be aware of more than it should (let alone the developer have to constantly retype everything just so they can access a file).
And for those who like to make sure the structure of their code follows the organizational structure of the files and directories on the disk, it gives us the ability to organize our projects exactly like that.
Even with all of that said, this is just one way and a few advantages of namespaces and autoloading. More advanced topics are covered in the PHP manual and in other open-source projects that I recommend you review if you have time.
In the next tutorial, we'll wrap up this series by applying what we've learned in this tutorial as we introduce namespaces and autoloading to our WordPress plugin. Until then, if you're looking for other WordPress-related material, you can find all of my previous tutorials on my profile page and you can follow me on my blog or on Twitter.
Don't hesitate to leave any outstanding questions you may have about namespaces, autoloading, or WordPress in the form below.