wordpress development tools and best practices

32
WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13 WordPress Development Tools and Best Practices di DANILO ERCOLI sabato 9 febbraio 13

Upload: danilo-ercoli

Post on 17-May-2015

5.978 views

Category:

Technology


2 download

TRANSCRIPT

Page 1: WordPress Development Tools and Best Practices

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

WordPress Development Tools and Best Practices

di DANILO ERCOLI

sabato 9 febbraio 13

Page 2: WordPress Development Tools and Best Practices

AGENDA

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

• The WordPress Codex

• Coding Standards

• wpshell and wp-cli

• Deferred Execution: jobs system

• Escape and Sanitize

• Enqueue scripts and styles

• Caching

sabato 9 febbraio 13

Page 3: WordPress Development Tools and Best Practices

WORDPRESS DEVELOPMENT TOOLS

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

sabato 9 febbraio 13

Page 4: WordPress Development Tools and Best Practices

THE WORDPRESS CODEX

•The online manual for WordPress Developers

•http://codex.wordpress.org

•The Codex is a wiki, meaning anyone can edit it. It grows and thrives off of individual contributions from people like you

•WordPress Coding Standards

http://codex.wordpress.org/WordPress_Coding_Standards

General information about coding standards for WordPress development

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

sabato 9 febbraio 13

Page 5: WordPress Development Tools and Best Practices

THE WORDPRESS CODEX

•Writing a Plugin

http://codex.wordpress.org/Writing_a_Plugin

The best starting place for learning about how to develop plugins

•Working with Themes

https://codex.wordpress.org/Theme_Development

Shows the technical aspects of writing code to build your own Themes

•Data Validation

http://codex.wordpress.org/Data_Validation

A must-read for WordPress contributors. Describes the functions used by WordPress to validate and sanitize data. Developers should be familiar with these functions and ideas

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

sabato 9 febbraio 13

Page 6: WordPress Development Tools and Best Practices

WORDPRESS COMMAND LINE INTERFACE

Currently, there is only one way of talking to a WordPress installation: HTTP requests. Whether you use a web browser, an XML-RPC application or just wget, it’s still just HTTP underneath.

wp-cli allows you to control WordPress through the command-line.

There are internal commands like 'option' (manipulate options table values), 'user' (create, edit, or delete users), or 'post' (create, edit, or delete posts).

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

# Get the value of a certain optionwpcli option get my_option

wpcli user list  --blog=mioblog.wordpress.com

wpcli theme status --blog=mioblog.wordpress.com

# Activate a newly installed theme on a particular site in a multisite setupwpcli theme activate my-new-theme --blog=fooblog.example.com

sabato 9 febbraio 13

Page 7: WordPress Development Tools and Best Practices

WORDPRESS COMMAND LINE INTERFACE

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

https://github.com/wp-cli/wp-cli

wp-cli is far better than writing your own bin scripts for many reasons:

• Promotes reusability over one-off or poorly architected scripts

• The real value in this is automation and seamless integration with other tools:

cron jobs, deployment scripts etc

• Many built-in tools like WP_CLI::line() which ensure your code is simply the logic

you need to execute

• There already are several popular plugins that work with wp-cli.

If you’re using WP Super-Cache, you can run the following command:

wp super-cache flush

sabato 9 febbraio 13

Page 8: WordPress Development Tools and Best Practices

WPSHELL

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

• wpshell is a command line shell suitable for any php project, includes code indexing, searching, and displaying built-in

• It gives you a command shell that accepts native PHP code as well as all the functionality your regular WordPress install would give you

• http://code.trac.wordpress.org/ - http://hitchhackerguide.com/2011/11/13/wpshell-a-shell-for-wordpress/

• This is intended for advanced developers. If you don’t know what you’re doing you can easily mess up your WordPress install. You can delete posts/users/anything in few commands

• I would not run this on production, but only in a local development environment. We will run it in production on WordPress.com (but rollback is easy there)

• Examples!

sabato 9 febbraio 13

Page 9: WordPress Development Tools and Best Practices

DEBUG PLUGINS

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

• Debug Bar

http://wordpress.org/extend/plugins/debug-bar/

Adds a debug menu to the admin bar that shows query, cache, and other helpful debugging information.

• Debug-Bar-Extender

http://wordpress.org/extend/plugins/debug-bar-extender/

Extends the debug-bar plugin with additional tabs to measure runtimes between checkpoints and lookup variable content. (Do not use in a production site).

• Debug Bar Console

http://wordpress.org/extend/plugins/debug-bar-console/

Adds a PHP/MySQL console to the debug bar. Requires the debug bar plugin.

sabato 9 febbraio 13

Page 10: WordPress Development Tools and Best Practices

DEFERRED EXECUTION - JOBS SYSTEM

PHP, as we all know, executes in a single threaded manner. That is the interpreter does A, then B, then C, then D, then finishes, and wipes its slate clean (shared nothing.)

It does this same things for every page view on your site.

For example, You have a social networking site that allows your users to send each other messages, the execution for that action might be something like this:

• setup web environment

• setup user environment

• check user permissions

• check message to make sure its not spam

• check message to make sure its not a duplicate

• check message for bad language

• insert the message into the db for the recipient(s)

• send out email to remote user(s) letting them know that they have a message waiting for them now

• render the "message sent" page for the sender

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

sabato 9 febbraio 13

Page 11: WordPress Development Tools and Best Practices

DEFERRED EXECUTION - JOBS SYSTEM

The jobs system changes everything.

With the jobs system you can stash the message into a job after checking permissions, and skip straight to rendering the "message sent" page.

Another process elsewhere on your network will pick up the job, pull out the message, check it for duplication, spam, language, stick it in the db if that all passes, and then finally send out emails to all the recipients.

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

Examples, The Jobs System in Action!

sabato 9 febbraio 13

Page 12: WordPress Development Tools and Best Practices

DEFERRED EXECUTION - JOBS SYSTEM

• A Web user interface to tell you what’s going on.

• A distributed fault tolerant crontab replacement.

• Statistics on your servers and your jobs.

• Error logs -- any output of a failed job (including STDERR output) is recorded along with the job in the db accessible from the UI.

• Scaleability -- setup multiple jobs clusters or add new servers to the existing one. Adding new servers happens automatically, just works. Different servers can be told how many simultaneous workers they're allowed right from the web UI

• Integration -- As a PHP application it's meant to, literally, include your whole code base allowing your environment to be accessible with no differences at all to developers

• http://code.trac.wordpress.org/

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

sabato 9 febbraio 13

Page 13: WordPress Development Tools and Best Practices

DEFERRED EXECUTION - JOBS SYSTEM

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

sabato 9 febbraio 13

Page 14: WordPress Development Tools and Best Practices

CACHING

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

sabato 9 febbraio 13

Page 15: WordPress Development Tools and Best Practices

DIFFERENT TYPES OF CACHING

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

Full page caching

•WP Super Cache•Batcache•W3 Total Cache

Object level caching with native caching APIs

•W3 Total Cache•WP File Cache•APC•Memcached Object Cache

sabato 9 febbraio 13

Page 16: WordPress Development Tools and Best Practices

FULL PAGE CACHE: BATCACHE

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

What is Batcache?

Batcache is a plugin to store and serve cached versions of rendered pages.

• Batcache uses memcached as its storage and is aimed at preventing a flood of traffic from breaking your site. It does this by serving old pages to new users.

• This reduces the demand on the web server CPU and the database. It also means some people may see a page that is up to 5 minutes old.

•Development testing showed a 40x reduction in page generation times: pages generated in 200ms were served from the cache in 5ms.

• Traffic simulations with Siege demonstrate that WordPress can handle up to twenty times more traffic with Batcache installed.

sabato 9 febbraio 13

Page 17: WordPress Development Tools and Best Practices

PAGE CACHE: BATCACHE

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

Who receives a cached pageview?

• By default, all new users receive a cached pageview.

• New users are defined as anybody who hasn’t interacted with your domain —once they’ve left a comment or logged in, their cookies will ensure they get fresh pages.

• Note that URLs with query strings are automatically exempt from Batcache.

$batcache['max_age'] = 300; // Expire batcache items aged this many seconds (zero to disable it)

$batcache['times'] = 4; // Only batcache a page after it is accessed this many times.

sabato 9 febbraio 13

Page 18: WordPress Development Tools and Best Practices

PAGE CACHE: BATCACHE

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

Because Batcache caches fully rendered pages, per-user interactions on the server-side can be problematic.

This means usage of objects/functions like $_COOKIE, setcookie,$_SERVER['HTTP_USER_AGENT'], and anything that’s unique to an individual user cannot be relied on as the values may be cached and cross-pollution can occur.

In most cases, any user-level interactions should be moved to client-side using JavaScript.

In some cases, we can help you set up Batcache variants if you’re limiting your interactions to a small set of distinct groups.(e.g. serve different content for users depending on whether the cookie “customer-type” is set, or equals “paid” or “pending”). Please get in touch if this something you’re interested in setting up.

sabato 9 febbraio 13

Page 19: WordPress Development Tools and Best Practices

PAGE CACHE: BATCACHE

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

if ( Jetpack_User_Agent_Info::is_blackbeberry() ) {

" $batcache['unique']['mobile'] = 'blackberry';

} elseif ( Jetpack_User_Agent_Info::is_WindowsPhone7() ) {

" " $batcache['unique']['mobile'] = 'windows-phone7';"

} elseif ( Jetpack_User_Agent_Info::is_S60_OSSBrowser() ) {

" $batcache['unique']['mobile'] = 'dumb';

} elseif ( in_array( jetpack_is_mobile( 'smart', true ), array( 'iphone' ) ) ) {

" $batcache['unique']['mobile'] = 'iphone';

} elseif ( jetpack_is_mobile( 'dumb' ) ) {

" $batcache['unique']['mobile'] = 'dumb';

}

Batcache Variants

sabato 9 febbraio 13

Page 20: WordPress Development Tools and Best Practices

WORDPRESS' NATIVE CACHING APIS

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

Transients

• Persistent out of the box• Stored in wp_options: _transient_{key} • WordPress uses for certain internal functions • set_, get_, and delete_transient()

Object Cache

•Not persistent without a plugin, such as W3 Total Cache or Memcached Object Cache•Storage depends on server's and plugin's capabilities•Used extensively within WordPress Cache objects can be grouped wp_cache_add(), _set, _get, _delete

sabato 9 febbraio 13

Page 21: WordPress Development Tools and Best Practices

BEST PRACTICES

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

sabato 9 febbraio 13

Page 22: WordPress Development Tools and Best Practices

CODINGS STANDARDS (1)

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

•Single quotes unless you need to evaluate a variable

<?php echo 'a great string'; ?>

vs

<?php $dog_name = 'Winston';

echo "my dog's name is: $dog_name"; ?>

•Naming is important

$myGreatVariable = 2; //not so much

$my_great_variable = my_function(); //Correct

sabato 9 febbraio 13

Page 23: WordPress Development Tools and Best Practices

CODINGS STANDARDS (2)

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

•Yoda conditionsif ( $city == 'Montreal' )

vs.

if ( 'Montreal' == $city )

•Don’t get too clever

isset( $var ) || $var = some_function();

Easier to read:

if ( ! isset( $var ) )

$var = some_function();

sabato 9 febbraio 13

Page 24: WordPress Development Tools and Best Practices

PROPERLY VALIDATE, SANITIZE, AND ESCAPE YOUR DATA

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

Your code works, but is it safe?

Rule No. 1: Trust Nobody

The idea is that you should not assume that any data entered by the user is safe. Nor should you assume that the data you’ve retrieved from the database is safe – even if you had made it ‘safe’ prior to inserting it there.

•In fact, whether data can be considered ‘safe’ makes no sense without context.

•Sometimes the same data may be used in multiple contexts on the same page.

Rule No. 2: Validate on Input, Escape on Output

To escape is to take the data you may already have and help secure it prior to rendering it for the end user

sabato 9 febbraio 13

Page 25: WordPress Development Tools and Best Practices

VALIDATING: CHECKING USER INPUT

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

To validate is to ensure the data you’ve requested of the user matches what they’ve submitted.

There are several core methods you can use for input validation; usage obviously depends on the type of fields you’d like to validate.

http://codex.wordpress.org/Data_Validation#Input_Validation

Let’s take a look at an example.

<input id="my-zipcode" type="text" maxlength="5" name="my-zipcode" />

We’ve limited the input to five characters of input, but there’s no limitation on what they can input. They could enter “11221″ or “eval(“. Or even more characters if they change the HTML.

sabato 9 febbraio 13

Page 26: WordPress Development Tools and Best Practices

VALIDATING: CHECKING USER INPUT

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

1  $safe_zipcode  =  intval(  $_POST['my-­‐zipcode']  );

2  if  (  !  $safe_zipcode  )

3      $safe_zipcode  =  '';

4  update_post_meta(  $post-­‐>ID,  'my_zipcode',  $safe_zipcode  );

The intval() function casts user input as an integer, and defaults to zero if the input was a non-numeric value.

We then check to see if the value ended up as zero. If it did, we’ll save an empty value to the database. Otherwise, we’ll save the properly validated zipcode.

sabato 9 febbraio 13

Page 27: WordPress Development Tools and Best Practices

SANITIZING: CLEANING USER INPUT

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

Whereas validation is concerned with making sure data is valid – data sanitization is about making it safe. Even ‘valid’ data might be unsafe in certain contexts.

You cannot ask “How do I make this data safe?”. Instead you should ask, “How do I make this data safe for using it in X”.

<input  id="title"  type="text"  name="title"  />

Tex$title  =  sanitize_text_field(  $_POST['title']  );2

update_post_meta(  $post-­‐>ID,  'title',  $title  );t

We could sanitize the data with the sanitize_text_field() function:

sabato 9 febbraio 13

Page 28: WordPress Development Tools and Best Practices

SANITIZING: CLEANING USER INPUT

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

Behinds the scenes, the function does the following:

•Checks for invalid UTF-8

•Converts single < characters to entity

• Strips all tags

•Remove line breaks, tabs and extra white space

• Strip octets

The sanitize_*() class of helper functions are super nice for us, as they ensure we’re ending up with safe data and require minimal effort on our part.

sabato 9 febbraio 13

Page 29: WordPress Development Tools and Best Practices

ESCAPING: SECURING OUTPUT

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

For security on the other end of the spectrum, we have escaping. To escape is to take the data you may already have and help secure it prior to rendering it for the end user.

WordPress thankfully has a few helper functions we can use for most of what we’ll commonly need to do:

esc_html() we should use anytime our HTML element encloses a section of data we’re outputting.

</pre><h4><!-­‐-­‐?php  echo  esc_html(  $title  );  ?-­‐-­‐></h4><pre>

esc_url() should be used on all URLs, including those in the ‘src’ and ‘href’ attributes of an HTML element.

<img  alt=""  src="<?php  echo  esc_url(  $great_user_picture_url  );  ?>"  />

sabato 9 febbraio 13

Page 30: WordPress Development Tools and Best Practices

ESCAPING: SECURING OUTPUT

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

esc_js() is intended for inline JavaScript.

var  value  =  '<?php  echo  esc_js(  $value  );  ?>';

esc_attr() can be used on everything else that’s printed into an HTML element’s attribute.

<ul  class="<?php  echo  esc_attr(  $stored_class  );  ?>">

It’s important to note that most WordPress functions properly prepare the data for output, and you don’t need to escape again.

<h4><?php  the_title();  ?></h4>

sabato 9 febbraio 13

Page 31: WordPress Development Tools and Best Practices

JAVASCRIPT & CSS

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

•Use wp_register_script() and wp_enqueue_script() to initialize your JavaScript files. This ensures compatibility with other plugins and avoids conflicts.

• The jQuery version that is packaged with WordPress is in compatibility mode. This means that jQuery() needs to be explicitly used, not the $() short form.

• If you need to register a script that is not part of WordPress, or your theme, make sure to use a packed version if available and make sure that their servers are up for the traffic you will request from them. Fail gracefully.

•Use wp_enqueue_style() to load stylesheets

•Make sure to use relative paths for URLs in your stylesheet.

• Avoid generating style definitions with PHP, as having a static CSS file delivered from CDNs is much faster than generating a style via a PHP script.

sabato 9 febbraio 13

Page 32: WordPress Development Tools and Best Practices

WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13

Danilo Ercoli

RELATORE

Web: http://daniloercoli.wordpress.com

Twitter: @daniloercoli

Danilo ha più di 10 anni di esperienza nello sviluppo di soluzioni software per il web e per il mobile. Ha lavorato con i più disparati linguaggi di programmazione, dall’assembler a SmallTalk, dal C all’ Object-C passando per Lisp, Java e PHP. Sviluppatore certificato PHP e Java2 SE. Molto tempo fa ha anche scritto un compilatore per il linguaggio Tiger. Attualmente lavora in WordPress.com passando gran parte del tempo sviluppando le soluzioni mobili offerte da WordPress e sviluppando componenti server a supporto del mobile. Lead Developer di WordPress for BlackBerry and PlayBook.

BIO

sabato 9 febbraio 13