PHP The right way – Coding practices

1. DATE & TIME:

– Datetime: class name helps to read, write, compare and calculate with date and time .

– DateInterval: class name calculate with DateTime, use instead of code that assumes same number of seconds in every day, both daylight saving and timezone alterations.

<?php
// create a copy of $start and add one month and 6 days
$end = clone $start;
$end->add(new DateInterval('P1M6D'));

$diff = $end->diff($start);
echo 'Difference: ' . $diff->format('%m month, %d days (total: %a days)') . "\n";
// Difference: 1 month, 6 days (total: 37 days)

– DatePeriod: iterate over recurring events.

– A popular PHP API extension is Carbon.

2. DESIGN PATTERNS:

– Factory: a class simply creates the object you want to use

– Singleton:

– Strategy:

– Front Controller:

– MVC:

 

PHP The right way – Dependency Management

– Project dependencies: PHP Libraries, frameworks, components…

– Two major package management systems for PHP: Composer & PEAR

– Composer:

  • Is dependency manager for PHP. List of project’s dependencies is composer.json.
  • Packagist, the official repository for Composer-compatible PHP libraries.

– PEAR:

  • Requires each package to have a specific structure, which means that the author of the package must prepare it for usage with PEAR. Using a project which was not prepared to work with PEAR is not possible.
  • 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.

PHP Right Way – Language Highlights

– PHP:

  • Involved dramatically over some years
  • Add a solid object-oriented model in PHP 5.0
  • Add anonymous functions and namespaces in PHP 5.3
  • Add traits (method of code reuse) in PHP 5.4

– Object-oriented Programming: support classes, abstract classes, interfaces, inheritance, constructors, cloning, exceptions, and more.

(http://php.net/language.oop5, http://php.net/language.oop5.traits)

– Functional Programming:

  • First-class function: A function can be assigned to a variable
  • Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.

    <?php
    $input = array(1, 2, 3, 4, 5, 6);
    
    // Creates a new anonymous function and assigns it to a variable
    $filter_even = function($item) {
        return ($item % 2) == 0;
    };
    
    // Built-in array_filter accepts both the data and the function
    $output = array_filter($input, $filter_even);
    
    // The function doesn't need to be assigned to a variable. This is valid too:
    $output = array_filter($input, function($item) {
        return ($item % 2) == 0;
    });
    
    print_r($output);

– Meta Programming:

  • Magic Method:

__get(), __set(), __clone(), __toString(), __invoke()

  • Reflection API:

– Namespace: two files with same name can co-exist in the separate directories, without fear of colliding with other libraries.

– Standard PHP Library(SPL): collection of classes and functions, made up primarily of commonly needed datastructure classes (stack, queue, heap, and so on)

– Command Line  Interface (CLI)

– xDebug:

 

 

PHP Right Way – The Code Styles Guide

– Ideally we should write PHP code that adheres to a known standard.

– PSRs: PHP Standards Recommendation. (http://www.php-fig.org/psr/)

– PHP_CodeSniffer : use to check code against any one of the recommendations (the plugin for text editor like Sublime Text to be given real-time feedback)

– Tools to fix the code layout automatically:

Example:

phpcs -sw --standard=PSR2 file.php --> show errors and subscribe to fix them. (helpful to include in git hook)
phpcbf -w --standard=PSR2 file.php --> fix the code layout problem reported. 

Senior PHP Developer – Update 6.2015

1. PHP Framework: Symfony, Zend, CakePHP , Yii…
2. Javascript:
+ NodeJs (Express Framework)
+ AngularJs
+ (Ember.js, Backbone, …)
3. CMS:
+ Laravel
+ WordPress
+ Magento
4. HTML:
+ HTML5, XHTML, CSS, CSS3
+ Bootstrap
+ (Foundation, SASS)
5. No SQL Database, Jenkins, MongoDB
6. SVN, Git
7. Building APIs + working with them
8. Elastic Search
9. Testing:
+ PHP Unit
+ Opensoure Library: forl logging, wiring, testing…

Cách học tiếng Anh thần kỳ

Tiếng Anh thần kỳ

1. Tư duy khoa học của việc học tiếng Anh:
Nghe nói trước tiên, sau đó là đọc, viết
Nhớ 1 từ khi nghe/thấy/viết 30 lần trở lên và trong ngữ cảnh hiểu được.
Giỏi ngữ pháp là kết quả của đọc sách nhiều.
Dùng tiếng Anh như phản xạ thì nghe đi, nghe lại, đọc đi đọc lại 1 lượng thông tin
Muốn tiến bộ nhanh thì phải học không bỏ ngày nào

2. Phương pháp:
– Coi phim có sub
– Luyện 3 cái phát âm
– Học 120 bài Listening Practice Through Dictation:
+ Nghe đi nghe lại và vừa nghe vừa nhìn transcript, không đc tra từ điển => phải biết các từ, các câu, các bài ta nghe nó phát âm thế nào, viết ra làm sao
+ Nghe khoảng 1 tháng, thì viết lại và tra từ điển
+ Học thuộc lòng = đọc lại đoạn văn ko nhìn transcript + biết đc nghĩa câu mình đọc
– Học tương tự cho Effortless của AJ Hoge (ko cần học thuộc)
+ Power English Now( thật kỹ và sâu Mini Story and POW – Học ngữ pháp 1 cách tự nhiên)

3. Lịch học: (2 năm – 4h/ 1 ngày)
6 tháng đầu
– 80 ngày đầu tiên:
+ Nghe listening 1 + 2: 1 ngày 10 bài, mỗi bài nghe 10 lần trong 10 ngày, chuyển sang 10 bài tiếp theo.
+ Học phát âm American Spoken English, Pronounciation Workshop, Master the American Accents: 1 hour/1 ngày
+ Xem phim Friends 2 tập/ 1 ngày

– 48 ngày kế tiếp:
+ Nghe listening 2 + 3: 1 ngày 10 bài, mỗi bài nghe 8 lần trong vòng 12 ngày, chuyển sang 10 bài tiếp theo
+ Đọc lại Listening 1 thành tiếng. 1 ngày 10 bài, mỗi bài đọc 2 lần trong 12 ngày, chuyển sang 10 bài tiếp theo
+ Xem phim Friends 2 tập/ 1 ngày

– 60 ngày kế tiếp:
+ Nghe listening 3 + 4: 1 ngày 10 bài, mỗi bài nghe 6 lần trong vòng 15 ngày, chuyển sang 10 bài tiếp theo
+ Đọc lại Listening 2 thành tiếng. 1 ngày 10 bài, mỗi bài đọc 2 lần trong 15 ngày, chuyển sang 10 bài tiếp theo
+ Chép lại listening 1. Mỗi ngày chép 1 bài, chép 2 lần, chép xong học thuộc
+ Xem phim Friends 2 tập/ 1 ngày

– 4 tháng tiếp theo:
+ Nghe 30 bài ministory. 1 ngày 3 bài, mỗi bài 4 lần trong 12 ngày, chuyển sang 3 bài tiếp theo.
+ Đọc lại Listening 3 + 4 thành tiếng. 1 ngày 10 bài, mỗi bài đọc 2 lần trong 12 ngày, chuyển sang 10 bài tiếp theo
+ Chép lại listening 2, 3, 4. Mỗi ngày chép 1 bài, chép 2 lần, chép xong học thuộc
+ Nghe xong đọc lại Ministory 1 – 6. 1 ngày 3 bài, mỗi bài 1 lần trong 12 ngày, chuyển sang 3 bài tiếp theo.
+ Xem phim Friends 2 tập/ 1 ngày

– 2 tháng tiếp theo:
+ Nghe 22 bài POV. 1 ngày 7 bài, mỗi bài 2 lần trong 20 ngày, chuyển sang 7 bài tiếp theo.
+ Đọc lại Ministory 7-24 thành tiếng.1 ngày 3 bài, mỗi bài 1 lần trong 10 ngày, chuyển sang 3 bài tiếp theo.
+ Viết lại những bài ministory đã đọc. Hai ngày chép 1 bài, chép 1 lần, chép xong học thuộc.
+ Xem phim Friends 2 tập/ 1 ngày

– 1 năm tiếp theo (sẽ update)

Còn tiếp….

htaccess Cheatsheet

Here is a simple cheatsheet for the .htaccess file:

Enable Directory Browsing

Options +Indexes
## block a few types of files from showing
IndexIgnore *.wmv *.mp4 *.avi

Disable Directory Browsing

Options All -Indexes

Customize Error Messages

ErrorDocument 403 /forbidden.html
ErrorDocument 404 /notfound.html
ErrorDocument 500 /servererror.html

Get SSI working with HTML/SHTML

AddType text/html .html
AddType text/html .shtml
AddHandler server-parsed .html
AddHandler server-parsed .shtml
# AddHandler server-parsed .htm

Change Default Page (order is followed!)

DirectoryIndex myhome.htm index.htm index.php

Block Users from accessing the site

<limit GET POST PUT>
order deny,allow
deny from 202.54.122.33
deny from 8.70.44.53
deny from .spammers.com
allow from all
</limit>

Allow only LAN users

order deny,allow
deny from all
allow from 192.168.0.0/24

Redirect Visitors to New Page/Directory

Redirect oldpage.html http://www.domainname.com/newpage.html
Redirect /olddir http://www.domainname.com/newdir/

Block site from specific referrers

RewriteEngine on
RewriteCond %{HTTP_REFERER} site-to-block\.com [NC]
RewriteCond %{HTTP_REFERER} site-to-block-2\.com [NC]
RewriteRule .* - [F]

Block Hot Linking/Bandwidth hogging

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ - [F]

Want to show a “Stealing is Bad” message too?

Add this below the Hot Link Blocking code:

RewriteRule \.(gif|jpg)$ http://www.mydomain.com/dontsteal.gif [R,L]

Stop .htaccess (or any other file) from being viewed

<files file-name>
order allow,deny
deny from all
</files>

Avoid the 500 Error

# Avoid 500 error by passing charset
AddDefaultCharset utf-8

Grant CGI Access in a directory

Options +ExecCGI
AddHandler cgi-script cgi pl
# To enable all scripts in a directory use the following
# SetHandler cgi-script

Password Protecting Directories

Use the .htaccess Password Generator and follow the brief instructions!

Change Script Extensions

AddType application/x-httpd-php .gne

gne will now be treated as PHP files! Similarly, x-httpd-cgi for CGI files, etc.

Use MD5 Digests

Performance may take a hit but if thats not a problem, this is a nice option to turn on.

ContentDigest On

The CheckSpelling Directive

From Jens Meiert: CheckSpelling corrects simple spelling errors (for example, if someone forgets a letter or if any character is just wrong). Just add CheckSpelling On to your htaccess file.

The ContentDigest Directive

As the Apache core features documentation says: “This directive enables the generation of Content-MD5 headers as defined in RFC1864 respectively RFC2068. The Content-MD5 header provides an end-to-end message integrity check (MIC) of the entity-body. A proxy or client may check this header for detecting accidental modification of the entity-body in transit.

Note that this can cause performance problems on your server since the message digest is computed on every request (the values are not cached). Content-MD5 is only sent for documents served by the core, and not by any module. For example, SSI documents, output from CGI scripts, and byte range responses do not have this header.”

To turn this on, just add ContentDigest On.

Enable Gzip – Save Bandwidth

# BEGIN GZIP
<ifmodule mod_deflate.c>
# Combine the below two lines - I've split it up for presentation
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css
  application/x-javascript application/javascript
</ifmodule>
# END GZIP

Turn off magic_quotes_gpc

# Only if you use PHP
<ifmodule mod_php4.c>
php_flag magic_quotes_gpc off
</ifmodule>

Set an Expires header and enable Cache-Control

<ifmodule mod_expires.c>
  ExpiresActive On
  ExpiresDefault "access plus 1 seconds"
  ExpiresByType text/html "access plus 7200 seconds"
  ExpiresByType image/gif "access plus 518400 seconds"
  ExpiresByType image/jpeg "access plus 518400 seconds"
  ExpiresByType image/png "access plus 518400 seconds"
  ExpiresByType text/css "access plus 518400 seconds"
  ExpiresByType text/javascript "access plus 216000 seconds"
  ExpiresByType application/x-javascript "access plus 216000 seconds"
</ifmodule>

<ifmodule mod_headers.c>
  # Cache specified files for 6 days
  <filesmatch "\.(ico|flv|jpg|jpeg|png|gif|css|swf)$">
  Header set Cache-Control "max-age=518400, public"
  </filesmatch>
  # Cache HTML files for a couple hours
  <filesmatch "\.(html|htm)$">
  Header set Cache-Control "max-age=7200, private, must-revalidate"
  </filesmatch>
  # Cache PDFs for a day
  <filesmatch "\.(pdf)$">
  Header set Cache-Control "max-age=86400, public"
  </filesmatch>
  # Cache Javascripts for 2.5 days
  <filesmatch "\.(js)$">
  Header set Cache-Control "max-age=216000, private"
  </filesmatch>
</ifmodule>

Setup SSL + WAMP 2.4

1)Install the Apache 2.2.11 (include OpenSSL) to work with openssl.

2) Create SSL Certificate and Key
a. Go To C:\OpenSSL-Win32

Copy C:\OpenSSL-Win32\openssl.cnf to C:\wamp\bin\apache\apache2.2.22\conf
Copy C:\OpenSSL-Win32\bin folder, copy all files to C:\wamp\bin\apache\apache2.2.22\bin

b. Open DOS command window by typing ‘cmd’ in your search menu.
c. Type this cd C:\wamp\bin\apache\apache2.2.22\bin
c. set OPENSSL_CONF=c:\[PATH TO YOUR OPENSSL DIRECTORY]\bin\openssl.cfg
d. Create a server private key with 1024 bits encryption by entering this command:
openssl genrsa -des3 -out server.key 1024

e. Remove the pass phrase from the RSA private key (while keeping a backup copy of the original file). Enter this:
copy server.key server.key.org
openssl rsa -in server.key.org -out server.key

f. Create a self-signed Certificate (X509 structure) with the RSA key you just created. Enter this:
openssl req -new -x509 -nodes -sha1 -days 365 -key server.key -out server.crt -config C:\wamp\bin\apache\apache2.2.22\conf\openssl.cnf

3. Copy the server.key and server.crt files

a. In the C:\wamp\bin\apache\Apache2.2.22\conf\, create two folders named as ssl.key and ssl.crt
b. Copy the server.key file to ssl.key folder and server.crt file to ssl.crt folder

4. Edit the httpd.conf file, php.ini, and httpd_ssl.conf

a. Open C:\wamp\bin\apache\apache2.2.22\conf\ httpd.conf file
b. Remove the comment ‘#’ at the line which says: LoadModule ssl_module modules/mod_ssl.so
c. Remove the commnet ‘#’ at the line which says: LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
c. Remove the comment ‘#’ at the line which says: Include conf/extra/httpd-ssl.conf

d. Open this file-> C:\wamp\bin\php\php5.3.13\php.ini
e. Remove the comment ‘;’ at the line which says: extension=php_openssl.dll
f. Open this file -> C:\wamp\bin\apache\Apache2.2.22\conf\extra\httpd_ssl.conf
g. Find the line which says: .
h. Right after it, change the line which says:

Change the line “DocumentRoot …” to DocumentRoot “C:/wamp/www/”
Change the line “ServerName…” to ServerName localhost:443
Change the line “ErrorLog….” to Errorlog “C:/wamp/bin/apache/Apache2.2.22/logs/sslerror.log”
Change the line “TransferLog ….” to TransferLog “C:/wamp/bin/apache/Apache2.2.22 /logs/sslaccess.log”
Change the line “SSLCertificateFile ….” to SSLCertificateFile “C:/wamp/bin/apache/Apache2.2.22 /conf/ssl.crt/server.crt”
Change the line “SSLCertificateKeyFile ….” to SSLCertificateKeyFile “C:/wamp/bin/apache/Apache2.2.22/conf/ssl.key/server.key”
Add the following lines inside those … tags:
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
Change the line “CustomLog…” to CustomLog “C:/wamp/bin/apache/Apache2.2.22/logs/ssl_request.log”

5. Make sure it works!
a. In the previous DOS Command windows, enter httpd -t . If it displays Sysntax is OK, then go to next step. If not, then correct the wrong syntax and redo step 3.
b. Restart the Apache server. If restart is successful, then open the browser and enter [localhost]
How it goes? Works, eh? Congratz!
Aaand lastly, to redirect non-https entered link to https, do this.
1. Open file C:/wamp/bin/apache/Apache2.2.22\conf\httpd.conf
2. Add this after the last line
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) []%{HTTP_HOST}%{REQUEST_URI}