William Jiang

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

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();
?>
Advertisements

SetEnvIf: Apache httpd log filter

SetEnvIf: Apache httpd log filter

My dedicated server’s (in godday.com) log files (error.log, access.log) are frequently accessed by google Googlebot and some engine spiders or from certain IPs, thus generate duplicated, useless log messages.
I have to filter these kind of messaghe to make logfile’s size increase not so quickly. I use ‘SetEnvIf‘ in httpd.conf to customize the log output to prevent such logging requests for both error.log and access.log.
Here is a detailed introduction of ‘SetEnvIf‘: How To Tell Apache To Not Log Certain Requests In Its Access Log?

The following are some ‘SetEnvIf‘ examples to filter certain IPs:

– To prevent all requests made with a certain browser, e.g. Internet Explorer, from getting logged:
SetEnvIf User_Agent “(MSIE)” dontlog

– To not log requests from any client whose hostname ends in bla.example.com, use:
SetEnvIf Remote_Host “bla.example.com$” dontlog

– To not log requests from any client whose hostname begins with example, use:
SetEnvIf Remote_Host “^example” dontlog

To not log requests from a certain IP address, use something like:
SetEnvIf Remote_Addr “192.168.0.154” dontlog

– If you don’t want requests of your robots.txt to get logged, use:
SetEnvIf Request_URI “^/robots.txt$” dontlog

– Apart from SetEnvIf, which is case-sensitive, you can use SetEnvIfNoCase which is case-insensitive.

For example, in order not to log certain search engine spiders, you could use:

SetEnvIFNoCase User-Agent "Slurp/cat" dontlog
SetEnvIFNoCase User-Agent "Ask Jeeves/Teoma" dontlog
SetEnvIFNoCase User-Agent "Googlebot" dontlog
SetEnvIFNoCase Remote_Host "fastsearch.net$" dontlog
– Or to not log certain file extensions, use something like this:
SetEnvIfNoCase Request_URI “.(gif)|(jpg)|(png)|(css)|(js)|(ico)|(eot)$” dontlog

– To not log certain referrals (e.g. from your own domain), use something like:
SetEnvIfNoCase Referer “www.mydomain.com” dontlog

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.

Another AngularJS email-list CRUD management demo

AngularJS email-list CRUD management sample

I wrote a sample demo by using angular-fullstack to demonstrate CRUD (create, retrieve, update, delete), pagination, sorting, search. It is pretty cool.
Compare to previous one, this demo includes more rich features – CRUD implementation.
The sample demonstrates a complete implementation of CRUD, could easily pickup and extensible to complex project.

  1. Codes: https://github.com/williamjxj/angular_emails

  2. Demo URL: http://dixitruth.com:9000/

To implement locally, first make sure your mongod is running, then:

 $ git clone ..;
 $ npm install
 $ bower install
 $ grunt serve

Then, visit http://localhost:9000 to see the demo!

It should work fine in various platform: Windows, Windows WebStorm IDE, CentOS, Mac etc.

Angular, Express, MongoDB demo

Angular, Express, MongoDB

I wrote a sample demo by using angular-fullstack to demonstrate pagination, sorting, search. It is pretty cool.

The demo demonstates a complete implementation of search, sort, pagination, could easily pickup and extendable to complex project.

  1. Codes: https://github.com/williamjxj/angularjs_mongodb

  2. Demo URL: http://dixitruth.com:9001/

To implement locally, first make sure your mongod is running, then:

 $ git clone ..;
 $ npm install
 $ bower install
 $ grunt serve

Then, visit http://localhost:9001 to see the demo!

CouchDB vs. Redis

CouchDB vs. Redis

I installed CouchDB, ZeroMQ in my MacBook Air, with the usages of XCode 5, brew.
The following are some helpful articles:

CouchDB,反Redis的产物?-Redis与CouchDB特性对比
Is CouchDB The Anti-Redis?
Cassandra、MongoDB、CouchDB、Redis、Riak、HBase比较

CouchDB 的长处正是Redis的短处:存储大量的不易变但会被经常查询的数据。Redis的长处正是CouchDB的短处:存储小量的常变数据。

IndexedDB -> CouchDB
localStorage -> Redis
Web Workers -> node promises/delay

JavaScript UI tips

Some tips for quick retrieving:

(1) MongoDB Windows GUI

http://robomongo.org/

(2) Node-Inspector / debugger

node-inspector: debug js, supervisor

(3) AngularJS

Karma / Testacular: JavaScript Test Runner
run in MINGW32 (git bash)

(4) Promise:

then(): http://promises-aplus.github.io/promises-spec/
Q(): https://github.com/kriskowal/q
It(callback) must use an explicit try block to catch the exception that JSON.parse might throw and must manually forward all errors to the subscriber. It also must take care not to call the subscriber inside the try block, since this would catch errors thrown by nodeback and throw them back at nodeback in the catch block. In general, writing callback-based functions that handle errors robustly is difficult and error-prone, and even if you do it right, rather verbose.
The second reward for using promises is that they implicitly guarantee that interfaces you create will be strictly asynchronous.

(5) log()
function log() {
  var local = /(localhost|127.0.0.1|192.168)/.test(location.href);
  if (local || typeof console.log === 'function') {
    console.log.apply(console, arguments);
  }
}
(6) WebStorm:
1. Code Analysis
Inspect Codes...
script:src (tab)

2. Keyboard Shortcuts
shortcutfoo.com
ctrl+shift+A

3. Actions
4. Templates
save as: Live Templates

5. Refactoring
function creation:
alt+enter

6. Navigation
7. Local History / Version Control
Changes -> Log
git history

8. External Tools (appear in TOOLS tab)
adding yeoman:
- yo angular
- npm install
- bower install
- common
- controller
- directive
- filter
- main
- route
- service
- view
mingw32 terminal / command-line

9. File Watchers
Coffee Script
10. Plugins
(7) Yeoman.io

Yeoman 1.0 is more than just a tool. It’s a workflow; a collection of tools and best practices working in harmony to make developing for the web even better.

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

nodejs pic

Node.js: the good parts flows

nodejs-the-good-parts-1

nodejs-the-good-parts-2

nodejs-the-good-parts-3

HighChartjs-NodeJs-MongoDB.png

Angularjs-Nodejs-Angular.png

Angular.js-Node-CouchDB