William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

Category Archives: Web Application

Vagrant in PhpStorm

Vagrant in PhpStorm – extend development environment

Vagrant(http://www.vagrantup.com/) is a very good PhpStorm add-on tool.
It creates and configures lightweight, reproducible, and portable development environments.

The following are the steps of how to use Vagrant in PhpStorm, extend the Windows-based PhpStorm development environment into a full-stack LAMP environment.

  1. Download 64-bit Vagrant for Windows. Install this .msi file (144MB) locally to C:Vagrant
  2. Then in PhpStorm: Ctrl+Shift+A -> Vagrant:
    – Vagrant executable: C:Vagrantbinvagrant.exe
    – Add Vagrant Box: lucid32

  3. in current PhpStorm project, Tools -> Vagrant -> Init in Project Root:
    generate a ‘Vagrantfile’ file.
  4. Modify the new generated Vagrantfile:
    config.vm.synced_folder "./", "/vagrant_mvc"

    This way share the whole project ‘/mvc/’ into the VM Linux machine

  5. Tools -> Vagrant -> Up
    (Re)boot the VM machine and mounting shared folders
  6. Tools -> Start SSH session …
    To ssh to this Linux Ubuntu lucid32 VM for details.
    – cd /vagrant_mvc
    — same file structures as within PhpStorm.
    — edit any file to immediately effected PhpStorm, coz the files are shared.

  7. To add LAMP tools into the VM, there is a good repository site: https://puphpet.com.
    https://puphpet.com has whole packages can be used into the VM machine:
    – VM OS (CentOS, Ubuntu, Debian
    – Server Packages
    – Webservers
    – Languages
    – Databases
    – etc
    By choose the defaults step by step to generate the Vagrant file and puphpet/ folder, copy them into PhpStorm’s current mvc/ directory,
    Reload the VM, all the LAMP-stack is download and installed. Very cool.
  8. This way creates a standard LAMP-full stack environment from the scratch to hold the whole project (here is ‘mvc’).
    Editable/Debugable by using PhpStorm, in the env of Linux (VM Server) as well as Windows.

Comparison of MySQL API options for PHP

Comparison of MySQL API options for PHP

The comparison table is from php.net, put here for easy retrieving:

  PHP’s mysqli Extension PDO (Using PDO MySQL Driver and MySQL Native Driver) PHP’s MySQL Extension
PHP version introduced 5.0 5.0 Prior to 3.0
Included with PHP 5.x yes yes Yes
MySQL development status Active development Active development as of PHP 5.3 Maintenance only
Recommended by MySQL for new projects Yes – preferred option Yes No
API supports Charsets Yes Yes No
API supports server-side Prepared Statements Yes Yes No
API supports client-side Prepared Statements No Yes No
API supports Stored Procedures Yes Yes No
API supports Multiple Statements Yes Most No
Supports all MySQL 4.1+ functionality Yes Most No

Summary: consider to use mysqli Extension first, then PDO, then MySQL native Extension.

PHP: Project logs setting other than webserver’s

PHP: Project logs setting other than webserver’s

It is important to configure PHP’s error reporting settings depending on which phase of development. Generally, it is a good idea to see all warnings and errors in the web browser during the initial phase; and later, once the site has launched, send error messages to a log file so that visitors do not see them.

1. Error Reporting for Development

During development, you want to display all errors and warnings to the browser.

// Report all PHP errors
ini_set('error_reporting', E_ALL);
// Set the display_errors directive to On
ini_set('display_errors', 1);

2. Error Reporting for Production

In production, you may want to lower the error reporting level and not display errors to the browser.

// Report simple running errors
ini_set('error_reporting', E_ALL ^ E_NOTICE);
// Set the display_errors directive to Off
ini_set('display_errors', 0);
// Log errors to the web server's error log
ini_set('log_errors', 1); 
ini_set('error_log', LOGDIR.'/error_log'); 

3. Logging errors

You can use the PHP function error_log() to send errors to your own log file or an e-mail address:

// Destinations
define("ADMIN_EMAIL", "nobody@site.com");
define("LOG_FILE", "/home/log/errors.log");
// Destination types
define("DEST_EMAIL", "1");
define("DEST_LOGFILE", "3");
/* Examples */
// Send an e-mail to the administrator
error_log("Fix me!", DEST_EMAIL, ADMIN_EMAIL);
// Write the error to our log file
error_log("Error", DEST_LOGFILE, LOG_FILE);

php PEAR and Composer

php PEAR and Composer

Currently there are two major package management systems for PHP – Composer and PEAR. Which one is right for you? The answer is both.

  • Use Composer when managing dependencies for a single project.
  • Use PEAR when managing dependencies for PHP as a whole on your system.

Some Agile Development framework, like Symfony2, laravel use Composer, while pear is used for general purpose.

1. PEAR

pear (http://pear2.php.net/) is a framework and distribution system for reusable PHP components. pear is short for “PHP Extension and Application Repository” and is pronounced just like the fruit. The purpose of PEAR is to provide:

  • A structured library of open-sourced code for PHP users
  • A system for code distribution and package maintenance
  • A standard style for code written in PHP
  • The PHP Foundation Classes (PFC)
  • The PHP Extension Community Library (PECL)
  • A web site, mailing lists and download mirrors to support the PHP/PEAR community

Pear installs packages globally, which means after installing them once they are available to all projects on that server. This can be good if many projects rely on the same package with the same version but might lead to problems if version conflicts between two projects arise.

$ pear list
Installed packages, channel pear.php.net:
=========================================
Package            Version State
Archive_Tar        1.3.7   stable
Console_Getopt     1.2.3   stable
MDB2               2.4.1   stable
MDB2_Driver_mysql  1.4.1   stable
MDB2_Driver_mysqli 1.4.1   stable
PEAR               1.9.4   stable
Structures_Graph   1.0.4   stable
XML_RPC            1.5.4   stable
XML_Util           1.2.1   stable

2. Composer

Composer (https://getcomposer.org/) is a tool for dependency management in PHP. It allows you to declare the dependent libraries your project needs and it will install them in your project for you.
Composer maybe borrowed from Node’s npm or Rails’ gem (RubyGems).

Composer is not a package manager. Yes, it deals with “packages” or libraries, but it manages them on a per-project basis, installing them in a directory (e.g. vendor) inside your project. By default it will never install anything globally. Thus, it is a dependency manager.

  • You have a project that depends on a number of libraries.
  • Some of those libraries depend on other libraries.
  • You declare the things you depend on.
  • Composer finds out which versions of which packages need to be installed, and installs them (meaning it downloads them into your project).

An example of composer.json is quite like package.json:

{
    "require": {
        "vendor/package": "1.3.2",
        "vendor/package2": "1.*",
        "vendor/package3": ">=2.0.3"
    }
}
//and to install dependencies(composer.json):
$ php composer.phar install

A good resource: PHP: The Right Way is an easy-to-read, quick reference for PHP popular coding standards, links to authoritative tutorials around the Web and what the contributors consider to be best practices at the present time.

php PEAR and Composer

php PEAR and Composer

Currently there are two major package management systems for PHP – Composer and PEAR. Which one is right for you? The answer is both.

  • Use Composer when managing dependencies for a single project.
  • Use PEAR when managing dependencies for PHP as a whole on your system.

Some Agile Development framework, like Symfony2, laravel use Composer, while pear is used for general purpose.

1. PEAR

pear (http://pear2.php.net/) is a framework and distribution system for reusable PHP components. pear is short for “PHP Extension and Application Repository” and is pronounced just like the fruit. The purpose of PEAR is to provide:

  • A structured library of open-sourced code for PHP users
  • A system for code distribution and package maintenance
  • A standard style for code written in PHP
  • The PHP Foundation Classes (PFC)
  • The PHP Extension Community Library (PECL)
  • A web site, mailing lists and download mirrors to support the PHP/PEAR community

Pear installs packages globally, which means after installing them once they are available to all projects on that server. This can be good if many projects rely on the same package with the same version but might lead to problems if version conflicts between two projects arise.

$ pear list
Installed packages, channel pear.php.net:
=========================================
Package            Version State
Archive_Tar        1.3.7   stable
Console_Getopt     1.2.3   stable
MDB2               2.4.1   stable
MDB2_Driver_mysql  1.4.1   stable
MDB2_Driver_mysqli 1.4.1   stable
PEAR               1.9.4   stable
Structures_Graph   1.0.4   stable
XML_RPC            1.5.4   stable
XML_Util           1.2.1   stable

2. Composer

Composer (https://getcomposer.org/) is a tool for dependency management in PHP. It allows you to declare the dependent libraries your project needs and it will install them in your project for you.
Composer maybe borrowed from Node’s npm or Rails’ gem (RubyGems).

Composer is not a package manager. Yes, it deals with “packages” or libraries, but it manages them on a per-project basis, installing them in a directory (e.g. vendor) inside your project. By default it will never install anything globally. Thus, it is a dependency manager.

  • You have a project that depends on a number of libraries.
  • Some of those libraries depend on other libraries.
  • You declare the things you depend on.
  • Composer finds out which versions of which packages need to be installed, and installs them (meaning it downloads them into your project).

An example of composer.json is quite like package.json:

{
    "require": {
        "vendor/package": "1.3.2",
        "vendor/package2": "1.*",
        "vendor/package3": ">=2.0.3"
    }
}
//and to install dependencies(composer.json):
$ php composer.phar install

A good resource: PHP: The Right Way is an easy-to-read, quick reference for PHP popular coding standards, links to authoritative tutorials around the Web and what the contributors consider to be best practices at the present time.

PDO, PDO-MySQL

I used PDO for somewhere, right now extract its document for a short summary:

1. What is PDO?

PHP Data Objects, or PDO, is a database abstraction layer specifically for PHP applications. PDO provides a consistent API for your PHP application regardless of the type of database server your application will connect to. In theory, if you are using the PDO API, you could switch the database server you used, from say Firebird to MySQL, and only need to make minor changes to your PHP code.

Other examples of database abstraction layers include JDBC for Java applications and DBI for Perl.

While PDO has its advantages, such as a clean, simple, portable API, its main disadvantage is that it doesn’t allow you to use all of the advanced features that are available in the latest versions of MySQL server. For example, PDO does not allow you to use MySQL’s support for Multiple Statements. PDO is implemented using the PHP extension framework, its source code is located in the directory ext/pdo.

2. What is the PDO MYSQL driver?

The PDO MYSQL driver is not an API as such, at least from the PHP programmer’s perspective. In fact the PDO MYSQL driver sits in the layer below PDO itself and provides MySQL-specific functionality. The programmer still calls the PDO API, but PDO uses the PDO MYSQL driver to carry out communication with the MySQL server.

The PDO MYSQL driver is one of several available PDO drivers. Other PDO drivers available include those for the Firebird and PostgreSQL database servers.

The PDO MYSQL driver is implemented using the PHP extension framework. Its source code is located in the directory ext/pdo_mysql. The following is an example of prepared statements.

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>

tips of using Jetbrains, xdebug and vim

The following are some summary using PhpStorm and vi.

1.vi: jump position

The following includes some strange symbols for vim, however useful:

Ctrl + o takes to previous location.
`. take you to the last change you made.
CTRL-O and CTRL-I seem to take you back and forth (Ctrl-o, Ctrl-i)

m[letter]
'[letter]
''
:marks

Redo / Undo
u: undo last change
Ctrl-R: Redo
U: return the last line which was modified to its original state

2. phpstorm

Excellent IDE: history, github integration, xdebug, code styles, ftp deployment, a lot of features which make development much easier.

// Always:
Ctrl + Shift + a

To navigate to a recently opened file: Ctrl+E
To navigate to a recently edited file:
Ctrl-Shift-E (recently opened file)
Ctrl-E (recently edited file)

Navigate a class, file or symbol with the specified name:
Class: Ctrl+N
File (directory): Ctrl+Shift+N
Symbol: Ctrl+Shift+Alt+N

To navigate to the next/previous change in the editor:
shortcuts: Ctrl+Shift+Alt+Down or Ctrl+Shift+Alt+Up.

Ctrl+b: open the function's source defination.
Ctrl+F12: show herited members.
Alt-click to close other files.

3. xdebug & phpStorm

By using XAMPP’s xdebug, and phpStorm, make drupal debug works in a web-application env.

To start Xdebug, you’ll need to append the XDEBUG_SESSION_START=xxx section to the url, i.e.:
http://localhost/drupal/index.php&XDEBUG_SESSION_START=random

It does not matter which browser you use, as long as the HTTP request is going to the apache/PHP server that has xdebug installed and configured.

Configuring XDebug with PHPStorm:

http://www.lullabot.com/blog/article/configuring-xdebug-osx-mountain-lion

4. Run node in webstorm

JetBrains’ Webstorm is fabulous. the ctrl+shift+a shortcut key is great, and git is pretty helpful.
Some useful shortcut keys:

PhpStorm Default Keymap – JetBrains

such as CTRL + SHIFT + F,
CTRL + R,
CTRL + ALT + I

Webstorm run/debug mean-stack

Webstorm run/debug mean-stack

I setup MEAN codes from http://www.mean.io/ in a Webstorm env.

  1. Make sure node.js, npm, bower, grunt are installed and accessible from WebStorm.
  2. Make sure Mongodb daemon is running (port: 27017)
  3. Use git gui or Webstorm -> VCS -> Version Control -> git to git mean stack from https://github.com/linnovate/mean.git
  4. Get into the new Webstorm project ‘mean’
  5. Add a new Run item ‘mean’:
    – Run -> Edit Configurations -> Add(+) -> Node.js:
    – Name: mean
    – Path to Node: C:Program Filesnodejsnode.exe
    – Working Directory: C:….WebstormProjectsmean
    – Path to Node APp JS File: C:….WebstormProjectsmeanserver.js
  6. Open the WebStorm settings(ctrl+alt+s), and then click the Command Line Tool Support.
  7. In the Command Line Tool Support page, click the Add button. Click Create Custom Tool dialog box (+).
  8. In the Tool Settings dialog box that opens, specify the following:
    — Tool name and location.
    — The alias to use in command calls instead of the full path to the tool.
    — Brief explanation of the tool functionality.
    For example, I use git bash:

    Tool Path:  "C:Program Files(x86)Gitbinsh.exe" --login -i
    Alias: git bash
    Description: debug mean project
  9. When you click OK, WebStorm brings you to the Command Line Tool Support page, where the new tool is added to the list of available tools.
  10. Choose from Tools -> External Tools -> git bash
  11. In the ‘git bash‘ command line, running:
    npm install //install modules in package.json
    bower install //install front-side angular DIs in bower.json
    
  12. If both the installation succeed, then:
    Run -> Run ‘mean’
  13. In browser: http://localhost:3000/

    It should work fine, a pretty cool CRUD application by using mongodb+express+angularjs+node.

  14. Debug should also work correctly. For the new added data, in ‘git bash’ command line:
    use mongo command to access MongoDB.

This is cool to run/debug mean demo in Webstorm environment.

JavaScript Tips

JavaScript Tips

A good book:Learning JavaScript Design Patterns, http://dixitruth.com/test/initializr/index.html

Some Summaries of tools sites
json formatter and validator
CSS processor
HTML-lpsum.com
css-tricks.com/css3-button-maker
spritebox.net
css3menu.com
50 web developing tools
addyosmani.com/resources/essentialjsdesignpatterns/book/
JS advanced codes
//1. namespace
var NS = NS || {
  Utils: {},
  Models: {},
  Views: {}
};

//2. Revealing Module Pattern:
NS.App = (function() {
  var init = function() {
    NS.Utils.log();
    this.welcome = new NS.Views.WelcomeScreen();
    this.welcome.showWelcome();
    this.news = new NS.Views.News();
    NS.Models.News.getNews();
  };
  return {
    init: init
  };
}());
NS.App.init();

(function($) {
  var m = 'private message';
  NS.Views.WelcomeScreen = function() {
    this.welcome = $('#welcome');
  };

  NS.Views.WelcomeScreen.prototype = {
    showWelcome: function(){
      this.welcome.html(m);
    }
  };
}(jQuery));

$(function() { NS.App.init(); });

// Observer pattern: pubsub
NS.Models.News = (function() {
  var url = '/some/news/';
  var getNews = function() {
    $.ajax({url:url,....success: newsRetrieved});
  };
  var newsRetrieved = function(news){
    AmplifyJS.publish('news-retrieved', news);
  }
  return {
    getNews: getNews
  }
}());

(function(){
  NS.Views.News = function(){
    this.news = $('#news');
    amplify.subscribe('news-retrieved', $.proxy(this.showNews));
  };

  NS.Views.prototype.showNews = function(news) {
    var self = this;
    $.each(news.function(article) { self.append(article); });
  }
}());

//3. compressors:
Grunt
Google Closure
JSMin
YUI Compressor
AMD: Asynchronous Module Definition

promise

From what I have understood there are three ways of calling asynchronous code:

  1. Events: eg. request.on(“event”), callback);
  2. Callbacks: eg. fs.open(path, flags, mode, callback);
  3. Promises

Promises in node.js promised to do some work and then had separate callbacks that would be executed for success and failure as well as handling timeouts. Another way to think of promises in node.js was that they were emitters that could emit only two events: success and error.

A Promise is a programming model that deals with deferred results in concurrent programming. The basic idea around promises are that rather than issuing a blocking call for a resource (IO, Network, etc.) you can immediately return a promise for a future value that will eventually be fulfilled. This allows you to write non-blocking logic that executes asynchronously without having to write a lot of synchronization and plumbing code.

More information:
Promises/A
jQuery Deferred
q: Defer/when style promise API for JavaScript

I use cujojs/when.js, and angularjs is Q library.