William Jiang

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

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.

using PhpStorm edit Remote PHP Project

using PhpStorm edit Remote PHP Project

I have a PhpStorm installed in local Windows, while having a remote CentOS 6.2 Server hoisted in godaddy.com.
How to edit ‘web apps reside in remote CentOS 6.2 Server’ within ‘local phpStorm env’?
Such as Laravel, Symfony2, cakePHP, worldpress project?
The following is the steps:

  1. Make sure a ftp server is running on centos 6.2, such as vsftpd. So local phpStorm can ftp access remote Linux server. In my CentOS 6.2:
    $ ps -e | grep ftp
    30261 ?        00:00:00 sftp-server

    mean the ftp server deamon is running.

  2. In PhpStorm IDE:
    File | New Project From Existing Files
    | Create New Project: Chooise Your Scenario
    | Web server is on remote host, files are accessible via FTP/SFTP/FTPS

  3. Make sure remote CentOS file directory’s permission is correctly: accessible, writable.
  4. Following the steps, config:
    – FTP Type. Here is SFTP (port 22)
    – remote file directory, e.g. /home/user/mvc/
    – remote web server root URL, e.g. http://example.com/
    – specify root folder on the remote server, e.g. /home/ussr/laravel/blog/
    – Specify project web path on remote server, e.g. http://example.com/laravel/blog/
    After done the config, it will auto sftp remote folder to locally PhpStorm Repository.
    Pretty cool!

  5. Now the new Prject can be editable in PhpStorm, using:
    Right click -> Upload to folder to sync the file.
  6. Also Menu -> Run to debug the updating. For debug, make sure XDEBUG is configured in both remote CentOS php.ini as well as local PhpStorm (Ctrl+Alt+S).
    So can debug remote web app in a local phpStorm environment.

  7. What else? It should work perfectly!

web server .htaccess

Web Server .htaccess routing example

For a PHP micro-framework and quick solution, using web-server’s (like Apache) URL rewrite(mod_rewrite) is a good choice. Just add/edit .htaccess file in specific/various dirs to control the URL routines. A standard .htaccess file:

RewriteEngine On
RewriteBase /name/

RewriteCond %{DOCUMENT_ROOT}/name/$1.php -f
RewriteRule ^([^/]+)/([^/]+)/?$ $.php1?action=$2 [L,NC,QSA]

RewriteCond %{DOCUMENT_ROOT}/name/$1.php -f    
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ $1.php?action=$2&id=$3 [L,NC,QSA]

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteRule ^(.*)$ $1.php [L]

This will convert a php HTTP request to a better meaningful URL:

//From HTTP Request:
routing.php
routing.php?action=create
routing.php?action=list&id=1

// To:
/routing
/routing/create
/routing/list/1

In this way, PHP doesn’t involve into routing request. Compared to PHP MVC framework and routine, it is faster, but less extensible and flexibility. A good URL rewriting example from CakePHP is at:

http://book.cakephp.org/2.0/en/installation/url-rewriting.html

Affecting PHP’s Behaviour

Affecting PHP’s Behaviour

While we are immersed in work, it is better to look up and think see if there is some shortcut way for the solution.
The following is from php.net, for PHP performance collection:

http://ca3.php.net/manual/en/refs.basic.php.php

  • APC — Alternative PHP Cache
  • APD — Advanced PHP debugger
  • bcompiler — PHP bytecode Compiler
  • BLENC — Blenc – BLowfish ENCoder for PHP source scripts
  • Error Handling — Error Handling and Logging
  • htscanner — htaccess-like support for all SAPIs
  • inclued — Inclusion hierarchy viewer
  • Output Control — Output Buffering Control
  • PHP Options/Info — PHP Options and Information
  • scream — Break the silence operator
  • Weakref — Weak References
  • WinCache — Windows Cache for PHP
  • Xhprof — Hierarchical Profiler

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 MySQLi: MySQL Improved Extension

There are three main API options when considering connecting to a MySQL database server:

  1. PHP’s MySQL Extension
  2. PHP’s mysqli Extension
  3. PHP Data Objects (PDO)

Each has its own advantages and disadvantages. By default we use ‘PHP MySQL extension’. Here focus on the second – MySQLi extension:
The mysqli extension is built using the PHP extension framework, its source code is located in the directory ext/mysqli.

According to wiki, MySQLi is an improved version of the older PHP MySQL driver, offering various benefits.
The MySQLi extension provides various benefits with respect to its predecessor, the most prominent of which are:

  • An object-oriented interface
  • Support for prepared statements
  • Support for multiple statements
  • Support for transactions
  • Enhanced debugging support
  • Embedded server support

The following is a quick example from php.net/mysqli‘s document page:

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") "
      . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($stmt = $mysqli->prepare("SELECT id, label FROM test ORDER BY id ASC"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
     echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!($res = $stmt->get_result())) {
    echo "Getting result set failed: (" . $stmt->errno . ") " . $stmt->error;
}

var_dump($res->fetch_all());
?>

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.

Perl Padre IDE

Perl Padre IDE, Catalyst, and others

Perl is good at text processing, the following are some examples:

1. Add space between words
my $text = "ThisTextWithoutSpaces";
$text =~ s/([a-z])([A-Z])/$1 $2/g;
print $text; # This Text Without Spaces
2. Get the size of a file in bytes
$size = -s “path/to/file.txt”;

3.Running Windows? Got a file with UNIX line endings?
perl -ne "s/n/rn/; print;" linux.txt > windows.txt
# This changes 'n' to 'tn', like tr "n" "rn" 
4. Want to make a table of the number of times each word in $text appears?
my %words = ();
$words{lc($_)}++ for $text =~ /b([w']+)b/g;

Each key of the %words hash will be a word in $text, and the value is the number of times that word appeared.

5. Padre, the Perl IDE
Padre is a Perl IDE, an integrated development environment, the url is http://padre.perlide.org/.
After install Padre which also install Perl latest version (5.14), then install Catalyst, the Perl MVC framework:

$ cpanm Catalyst::Devel
Follow

Get every new post delivered to your Inbox.

Join 75 other followers