Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

This Week I Learned 2018 - Week 16

Last week post or something from the archive.

看了一套墨西哥的戏,《行走距离》。电影讲述一个三百公斤的胖子,寄托于摄影以解生活的苦闷。间接中,也结交了几位好友,让他生命有所改善。没有惯性的情节,简单不过及现实的故事。健康是宝,平淡是福。

Another week of learning new English vocabulary. One issue with making sentences using these words was that the sentences was either too forceful or too literally (直译的) translated.
Sandy alleviates (缓解) the excruciating pain on her lower body part by elevating both legs into a bucket with warm water. By doing so, they hope it can obliterate (忘却) the pain she was going through. Both legs were swelling due to her falling into liquescent (易液化的) soil and stabbed by tree trunk while trekking in the wood. The swelling have worsen and everyone worry that the muscle may liquefy (使液化) from within. 

Stuck with an interesting MySQL problem, which was quite easy but I can't seem to get it right after several tries. Basically we want to update certain column in t1 to the maximum value from a group of similar records. The SQL query was quite straightforward, just join with the second table, t2 with maximum record with the first table, t1.
UPDATE t_transaction tu
JOIN (
    SELECT code, MAX(flag) AS flag
    FROM t_transaction
    GROUP BY code
) t
ON tu.code = t.code
SET tu.flag = t.flag

Modern backend developer in 2018? (via HN) A checklist and decision making tree are always a good choice to make good decision making when picking up new technology stack.

Perl constant array. Sometimes the simplest and easiest way is the only way instead of going through and abusing quirky Perl syntax.
use constant FRUITS => ['apple', 'orange', 'banana'];

my $fruit = 'apple';
if (!grep $fruit eq $_, @{+FRUITS}) {
    print "Is not a fruit";
} else {
    print "Is a fruit";
}

use constant FRUITS => qw(apple orange banana); 
use constant FRUITS => (apple orange banana);  
my $fruit = 'apple';
if (!grep $fruit eq $_, FRUITS) {
    print "Is not a fruit";
} else {
    print "Is a fruit";
}

Modern PHP without a framework. (via HN) Nah, still hate it after all these years. Maybe I'm just prefer a more prettier programming language.

回顾自己的工作生涯,真的必须自我检讨未来的工作方向,看看那些是自己重视的
所以,你得先釐清有哪些條件是你重視的,像薪水、公司品牌、職位、工作內容等,一一把它寫出來。列出條件後,再排定先後順序,之後,和你手邊的 offer(拿到手的工作)比較,做成表格。縱軸是你重視的條件,並依照先後順序,由上而下排列;橫軸則是你拿到的 offer。當你完成表格後,該選擇的工作就會自動「跳出來」。
當我們在思考應該向哪家公司投遞履歷時,其實已經在篩選公司了,但如果是以「錢多事少離家近」為標準,長遠而言卻未必是最適合自己的公司。所謂「知己知彼,百戰百勝」,此時應該要先釐清自己的需求,包括期望的上下班時間、喜歡的工作環境、想做內勤或外務、理想的管理方式、工作如何分配、會議如何進行、同事如何相處、以及有哪些學習機會等。再依這些喜好排出先後順序,然後評估要應徵哪些公司。
工作上要留下那个”人才“? 当然是人品态度优先,能力可以慢慢去培养。

What are some tech companies that do not use open floor plan? Interesting question for those who are looking to justify cubicles. The office at Fog Creek was in between, open space for collaboration and private office for working.

Data class in Python 3.7. (via HN) What took them so long? Syntactic sugar or not, this should have been in any fundamental data type for any programming that supports OOP.

Vipassana for Hackers. (via HN) A book on how a tech guy perceived and practiced Vipassana meditation without involving religion, just the practice. Contrary to typical meditation book, lots of pictures explaining the core concepts.

Moving for good. (via HN) Good write-up when you're moving to a new place. Key quote here (emphasis added),
Ask lots of questions. Ask them to explain things, and show you how it’s done. When they state a fact, ask how they know. When they state an opinion, ask for examples.
How to be a systems thinker. (via HN) I still can't get my head to understand this and the list of reading materials is quite long. Worth spend time on this? We shall see then.

This Week I Learned - 2017 Week 46

Last week post or something from the archive. For something interesting related to a week, visualize your life in week. How many weeks do you still left?

So much things I've learned and observed this week. Some were the same old same old, others were quite eye opening instead, if you pay close attention.

Encountered this message, "expected, at character offset 2 (before "(end of string)")", when processing the JSON file during encoding. It turned out the root cause is how we use the read_file subroutine in File::Slurp module. Passing the right parameter, you can have multiple ways to either read the whole file or multiple lines. There even a research done on finding the optimized way to do do.

You’re working in the wrong place. (if you’re working in an open office)". When most of the employee are wearing headphones, that sufficiently shows that open floor plan have failed to reach its original intention, which to promote so-called information sharing and collaboration. Why open office don't work? Have you ever been to a library to study? If everyone keeps talking or making noise, do you think you can concentrate on your stuff?

The Amazing $1 Microcontroller. (via HN) The author should have written a book instead of a very lengthy blog post. I agree with the author, it's an exciting time for picking up electronic.

Looping through an array in JavaScript. A simple programming language construct, yet so many ways and workarounds. Add to that, you have JQuery way (.each()) of looping through DOM elements with its own quirk. Not to mention the let vs. var. No wonder so many JavaScript transpilers exists. And I was thinking PHP or Perl was bad, JavaScript is even more mind boggling. Forget about JavaScript, just stick to TypeScript which is gaining momentum these days.

The LEBRON stack. Anyone still remember the MEAN stack? I believe only Node.js survived the hype so far. Something similar, do you know Slack is using PHP for its server-side application logic?

Getting things done? (via HN) There are just two steps. However, till today, I'm still struggle with the execution of the system. Refine and more refine.

1/ Start something simple, the first step.
2/ You can stop if you want to.

This Week I Learned - 2017 Week 45

Last week post or something from the archive.

So many things to learn and yet, so little time. But once you've understand it, most of these stuff are rather quite straightforward.

The local startup scene have moved from the early days of cloning social network and shopping to the current day of big data, machine learning, artificial intelligent, and blockchain. History will repeat itself again as illustrated in Gartner Hype Cycle. The hype cycle will eventually die down and new shinny things will emerge again. Does the local startups works? Partly yes and no. Only time will tell.

SSDD. Probably the best term I can think of describing the web stack right now, especially on the front end part. Endless things "reinvented" or rediscovered again and again and again. One thing for sure, there is a clear distinctive separation between the Front End and the Back End development.

NBA Go, the finest NBA score from command line. Sadly, it still doesn't display well under different terminals and the dependency on Node.js. Is Node.js is the new PHP? Is Node.js going to dethrone PHP? Yes, my survey and gut feeling indicates so.

Agile Product Ownership in a Nutshell. It's going to be a long adjustment and readjustment process to get it done, if possible, right. Managing requirements and stakeholders expectations outweighs the implementation. Furthermore, it's even more challenging for flat organization with different geographical offices and working cultures. Interesting development indeed and can't wait for the growth and expansion.

MSP430FR2433. Another new board from TI.

This Week I Learned - 2016 Week 51

Last week post or the whole series.

Week 51 of 2016. The last second week of the year. Lots of time to reflect and ponder about my past and future. Here is an video of interviews with three centenarians (those who live past 100 years) on their secrets for living so long. There maybe many years to go with your life but never overlook the issue of mortality. Learn as much as you can, do things you enjoy, and spend your time with someone who both of you are mutually care about.



List of single-file C/C++ libraries. Someone really needs to compile a bigger list. There are a lot that needs to be picked up by me when come to C++, mostly are all the fundamental stuff. Good example is do you know there are different types of memory allocated (stack, heap, bss, data, and text) for a program? That's why good fundamental of computing hardware is crucial being a system developer. Background on how Operating System works or manage the memory is something i severely lacking. Which is why I'm still having a hard time understanding the whole C++ compilation process (another good introduction with plenty of diagrams).

While we're on C++, if you are creating a new project, this can be the folder structure of the project you can follow. Between a macro, a function, or a class, just stick to something simple, use macro for creating debugging details.

Another interesting item caught my attention, conversion of other data type to string in C++ is not as straightforward as I assumed it is. There are many approaches, such as the standard C++ or C++03 way (using stringstream), the C++11 way (using std::to_string), or the Boost way (using boost::lexical_cast). Unless you're stuck with legacy C++ compiler, use the C++11 method. While we're looking at string, C++ being a static typed language, string manipulation have to be expressed in an explicit manner. For example, to pad a string to a certain size and characters as shown below.
std::cout 
<< std::left << std::setw(10) << std::setfill('.')
<< foobar << ": " << 42 << '\n';

// output
foobar....:42

Need to implement your own logging function? This is the time where you need to use a C++ macro. Otherwise how can you use the preprocessor macro like `__FILE__` or `__LINE__`?

Function pointer in C/C++. Useful when you have an array of items that point to a corresponding functions.

It has been a while since I ever look into PHP. Found two interesting libraries, Httpful and Underscore.php. Both are either direct port of influenced by similar libraries in other programming language. Not really sure about the current state of PHP but I glad I ended up doing something else other than PHP. It's always nice to code in different kind of programming languages.

Hook system in Perl? This needs a third party CPAN module like Hook::LexWrap. Otherwise, it can be quite hackish.

This Week I Learned - 2016 Week 40

Last week post or the whole series.

My sentiments exactly. See comment below regarding chasing fad in technology development and especially PHP programming language. Do I actually miss PHP? Not really. But I think most of the web development systems still can be solved using PHP-based solutions. Barrier of entry to web development using PHP still the best choice.
Incidentally, this isn't unique to the front-end. I've seen the same thing happen with the SQL->ORM->Mongo->Couch->SQL nonsense, or the myriad of templating engines written for PHP, a language that itself is a templating engine.

Using Node.js? Need a basic system with essential features to bootstrap your system? Look no further than Hackarthon Starter.

The difference between Ponzi, Pyramid, and Matrix Scheme. A lot of young people, especially fresh graduates need to aware and prevent themselves from falling for such scams. The pitch of being your own boss or retire early may sounds too good to be true.

Sometimes the documentation written for a certain API, Data::ICal was so confusing that you have to resolve to searching source code written by others using the same API itself at here, here, here, and here. Can't blame the API author as the standard itself, RFC 5455 is as confusing and complicated.

Google Interview University (via HN). Instead of working for a company, why not strive to work with great people instead? Google is so big and not every team is equal. Agree with one of the comment, this is a good compilation of resource for computer science study. Which reminds me again of the Programmer Competency Matrix. Instead of focusing on the computer science stuff, why not focusing on building stuff? Someone needs to read the interview of famous programmers on their background.

Getting older but still enjoy working as a programmer? Read Reflections of an "Old" Programmer, especially the comments from the blog post itself, HN, and Reddit. The main question here is how do you age gracefully as a programmer? Lifelong learning, especially the fundamentals (the core of computer science, not latest greatest fad frameworks), as those things never changed. I blogged about this last year, during my career detour as a non-programmer role, still technical though.

Didn't realize that to use PowerTop properly, first you will need to calibrate it after installation to collect measurement data. The whole process will take a while and networking will be disabled during that period.
$ sudo apt-get install powertop
$ sudo powertop --calibrate
$ sudo powertop --auto-tune

Besides that, you can turn off unwanted running services to save a bit more battery.
$ service --status-all

Upgrade to LXD 2.3 failed to due a spelling bug in bridge network upgrade script. Fixing the bug manually and restart the installation process again.
$ sudo apt-get install -f

However, new container created don't have a default network bridge. Re-enable this resolved the issue.
$ lxc network attach lxdbr0 test-alpine
$ lxc restart test-alpine

This Week I Learned - 2016 Week 36

Last week post or you might want to check out the whole series.

Some findings around the Internet.

XKCD-style graph using Matplotlib? In Ubuntu, you'll need to install these fonts to get the closest possible rendering.
$ sudo apt-get install ttf-mscorefonts-installer fonts-humor-sans
$ rm -rf ~/.cache/matplotlib/fontList.cache

Using Matplotlib without X-server? Switch to Agg backend. Useful when you're rendering image through Docker container.
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt

Sigh. Unresolved ImageMagick bug in most recently releases including the LTS, which text conversion still causing core dump. Switching to GraphicsMagick, a fork of ImageMagick did not resolve the issue as command line options have both diverted. My research made me aware that both tools were being used to massively batch process images in a very large scale.

Sometimes, the default Vim configurations/features is good enough without installing buggy extensions. We're relying too much on the external plugins without utilizing the fullest features of Vim itself.

Old time PHP developer switching to Perl? You should read this Reddit's post. The advice given was spot on and correlates with my own personal experience. Nothing against PHP, but in our journey to become a better developer, you'll need to expose yourself to other programming languages and environments. Otherwise you'll end up like those developer who claimed to be a ten-plus years developer but actually doing the same development development work for a year but repeated ten times. I will write another blog post on this in coming future.

"To finish projects on time, start every single step as late as possible" via HN. Full text of all the twitter posts. Catching and provocative statement coming from Tiago Forte, a productivity consultant. Despite the click bait title, HN user, bmh100 interpret his message correctly. Keywords here is "critical path". In other words, is Critical Chain Project Management. Sometimes I wonder is procrastination due to lack of awareness of a task? Or to rephrase it, procrastination is a mindfulness problem? Without awareness, there is no estimation and prioritization, hence the task will be postponed repeatedly or not completed within the time frame?

This Week I Learned - 2016 Week 24

Last week write-up or you might want to read the whole series.

Typosquatting programming language package managers. Mostly likely inspired by the Npm's left-pad incident.

Print debugging on steroid in PHP? Try Kint.

Due to the decommission of CPU processor by big Internet companies, the used market was flooded with Xeon E5-2670. Hence, there are many who tried to build a powerful Dual-Xeon machine. While the processor is roughly around USD 70 and highly soughtable, the motherboard is very costly. It's reasonable that everyone want to assembly the most powerful machine with minimum cost. However, judging by the TDP, it recommended to build smaller and more economical home lab. Again, it still depends on what the main purpose you want to build your own home lab.

tl;dr: Maintenance code: 3008.

Have an Unifi account with the Huawei EC6108V8 media player? Want to make the most of this tiny device? The essential configuration and setup steps are in post #10, #14, #32 (enable you to login to Play Store), #69, #90, #98, #102, #103, #178 (if #32 doesn't work), #190, #208 (similar to #178), #218 (maintenance code), #252, #263, #278 (similar to #178 and #208), #287, #291, #311, #319, #359, #377 (like #178), #387 (device specification), and #414.

This Week I Learned - 2016 Week 17

Write-up for last week or you might want to read the whole series.

Busy week, didn't follow up with anything else. Nothing but reading and writing papers.

Being a developer after 40? (HN thread) Are you too old for development? Nope. While general consensus is that if you over 35, you should either be in the management, start your own company, or be a consultant. But why you want to move on to something else? There is still so much to learn. Have fun, rest well, and keep yourself healthy. The first post of the discussion may shed some lights on the actual reason why organization are reluctant to hire more experience (often correlate with age) developer.

Learn a new technology each week in 2016. Awesome weekly project! Unfortunately, most of the project are written in Scala. Not that I've something against the programming language, but I've painful and dreadful slow experience setting up both Scala and Play framework. The main culprit is sbt, the interactive build tool. The number of dependencies to be downloaded in order to get sbt to work is so painful huge is like you're downloading the whole Internet. Furthermore, you really need a powerful development machine to do any development work in Java-based platform.

Pandoc (the universal document converter) with Markdown is awesome. But no one still can solve the annoying problem of making it easy to create a simple table. 

Why isn't Perl more popular? Reasons? Perl is a glorified AWK. The TMTOWTDI motto. Osborne effect of Perl 6PHP, the simplified version of Perl took over the web and dethroned Perl. No killer apps (like Rails for Ruby or WordPress for PHP).

Symfony Installation For Developer and System Administrator

Symfony, the PHP framework which has won the PHP framework market share as quite a few crucial PHP projects already transitioned or use either Symfony2 framework or its components. While I'm not a fan of Symfony due to its Javaism which introduces unnecessary complexity and divert from the original PHP design principles, but you can't ignore the influences it brought to PHP world.

Four years ago, I was evaluating it for a new project, but decided to go with CodeIgniter and Kohana due to project size and time frame. Always go for something you're familiar with instead venturing into new unknown territory. The money and time spent does not justify it. Everyone wants it fast, cheat, and don't really care about longevity of any projects. Enough ramblings, let us revisit the installation.

There are many ways to install or use Symfony framework but the recommended way is to use the Symfony installer. Although installation through Composer (deprecated), PEAR (deprecated), or GNU/Linux distros packages are still feasible.

First, getting the Symfony installer which you can obtain by downloading the binary directly and install locally. Popularized by those developer who want to have a universal quick installation method between GNU/Linux and MacOS. The Curl's -LsS parameter means that to download from a location (-L), silently (-s), but show errors (-S). Go to Explain Shell for the full parameters details.
$ sudo curl -LsS http://symfony.com/installer -o /usr/local/bin/symfony
$ sudo chmod a+x /usr/local/bin/symfony

Quick and convenient right? Indeed for developer point of view who want to bootstrap any application using Symfony framework quickly. However, for a system administrator, this is a big no-no, especially in production server, where priorities are targeted towards stability and security. Why so? Note that we should always verify the authenticity of any downloaded installer to check for any corruption or tampering. While there is way to verify Symfony components, we can't seem to find it for Symfony installer. Hence, such installation method, while convenient, lack assurances.

If you're a system administrator, surely you will prefer the default packages that come with your GNU/Linux distros. For sure, you are guarantee of well-tested and automated security updates. Something that is not possible if you install the Symfony framework manually where you've to keep track of any security advisories. The trade-off is that you've to stick with legacy but stable version of the framework which may not be supported anymore.

For example, in Fedora 22, which was release few weeks back, the available Symfony version is 2.5.11. Unfortunately, after checking release schedule and roadmap checker, there will be no support of security fixes after July 2015 and is advisable to upgrade to version 2.7.x.
$ dnf info php-symfony | grep Version
Version     : 2.5.11

If you're starting a new Symfony project, are you going to use the default and outdated Symfony packages that comes with your distro? Surely not. Who in the right mind will develop against an unsupported version? And furthermore, developer always like fancy new toys.

This is one of the dilemma when the distro packages is not catching up with the release cycle of the software. Another good example is in Fedora 22, there are still packages for PEAR channel for Symfony, where this is not supported anymore due to the transition to Composer. I'm not sure why Symfony 2.5 was selected but obviously there is a mismatch between the Fedora 22 and Symfony release timeline. Also, I think Centos 6 or 7 will have the similar unsupported version.
$ dnf search symfony | grep channel
php-channel-symfony.noarch : Adds symfony project channel to PEAR
php-channel-symfony2.noarch : Adds pear.symfony.com channel to PEAR

In the end, stick to the simpler way, using the Symfony installer, even though you may be some security risk but that can be prevented by verifying its components and using Security Advisories Checker tool..

Is Your Drupal Code Adheres to Coding Standards and Best Practices?

Following a coding standards and adhere to a best practices in any development environment is crucial to keep the code base consistent and every developer is aware of the default ways of development. For Drupal, there is this Coder module which helps to make sure your Drupal codes following the standard conventions and practices.

Before we install the Coder module, let's obtain some Drupal codes to be validated. We'll be using sample codes from Drupal Examples.
$ git clone git://git.drupal.org/project/examples.git drupal-examples

Install the Coder module using Composer. Note that I've tried installing using Drush but I still prefer the former way which is more suitable for general PHP library management.
$ composer global require drupal/coder

Changed current directory to /home/ang/.composer
Using version ^8.2 for drupal/coder
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing squizlabs/php_codesniffer (2.3.2)
    Downloading: 100%         

  - Installing drupal/coder (8.2.2)
    Cloning c08506a332235d5485c79231639e9577b8c4d332

Writing lock file
Generating autoload files

Checking the installed PHP CodeSniffer (phpcs) and PHP Code Beautifier and Fixer (phpcbf) program.
$ ll ~/.composer/vendor/bin/
total 0
lrwxrwxrwx. 1 ang ang 43 May 27 18:13 phpcbf -> ../squizlabs/php_codesniffer/scripts/phpcbf*
lrwxrwxrwx. 1 ang ang 42 May 27 18:13 phpcs -> ../squizlabs/php_codesniffer/scripts/phpcs*

However, both programs are not within Bash's program search path. Hence, we have to add it manually.
$ export PATH=$PATH:$HOME/.composer/vendor/bin

To make it permanent, just put the above line into ~/.bashrc or ~/.profile file.
$ echo "export PATH=$PATH:$HOME/.composer/vendor/bin" > ~/.bashrc

To verify our path has been set up correctly.
$ which phpcs
~/.composer/vendor/bin/phpcs

To test whether a sample code is adhere to Drupal coding standard. As shown below, the phpcs program can't find the Drupal coding standard rules file.
$ phpcs --standard=Drupal drupal-examples/action_example/action_example.module
ERROR: the "Drupal" coding standard is not installed. The installed coding standards are PSR1, PHPCS, Squiz, PSR2, Zend, PEAR and MySource

Set the path to the Drupal coding standard rules path and verify again.
$ phpcs --config-set installed_paths ~/.composer/vendor/drupal/coder/coder_sniffer
Config value "installed_paths" added successfully

$ phpcs -i
The installed coding standards are PSR1, PHPCS, Squiz, PSR2, Zend, PEAR, MySource, Drupal and DrupalPractice

Let's try again. Surprisingly the official Drupal examples code contains coding standards violation!
$ phpcs --standard=Drupal action_example/action_example.module 

FILE: ...ng/drupal-examples/action_example/action_example.module
----------------------------------------------------------------------
FOUND 13 ERRORS AND 2 WARNINGS AFFECTING 15 LINES
----------------------------------------------------------------------
 228 | ERROR   | [ ] Parameter comment must end with a full stop
 276 | ERROR   | [ ] Parameter comment must end with a full stop
 283 | ERROR   | [ ] Type hint "array" missing for $context
 285 | ERROR   | [x] Line indented incorrectly; expected 3 spaces, found 2
 286 | ERROR   | [x] Line indented incorrectly; expected 3 spaces, found 2
 287 | ERROR   | [x] Line indented incorrectly; expected 3 spaces, found 2
 288 | ERROR   | [x] Line indented incorrectly; expected 3 spaces, found 2
 289 | ERROR   | [x] Line indented incorrectly; expected 3 spaces, found 2
 290 | ERROR   | [x] Line indented incorrectly; expected 3 spaces, found 2
 291 | ERROR   | [x] Line indented incorrectly; expected 3 spaces, found 2
 292 | ERROR   | [x] Line indented incorrectly; expected 3 spaces, found 2
 293 | ERROR   | [x] Line indented incorrectly; expected 3 spaces, found 2
 343 | ERROR   | [ ] Type hint "array" missing for $context
 345 | WARNING | [ ] The use of function dsm() is discouraged
 346 | WARNING | [ ] The use of function dsm() is discouraged
----------------------------------------------------------------------
PHPCBF CAN FIX THE 9 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------

Time: 429ms; Memory: 7.5Mb

PHP Version Manager (PHPENV)

With the recently release PHP 5.6, I stumbled upon these tools, phpenv, (inspired by rbenv) and php-build which let you build different PHP versions without messing up your existing installation. For installation steps, we're following Kobito's setup guide.

1. To setup both phpenv and php-build, just type these commands. Be extra careful when running downloaded shell script directly from the net.

$ curl https://raw.github.com/CHH/phpenv/master/bin/phpenv-install.sh | bash
$ git clone git://github.com/CHH/php-build.git ~/.phpenv/plugins/php-build
$ echo 'export PATH="$HOME/.phpenv/bin:$PATH"' >> ~/.bashrc
$ echo 'eval "$(phpenv init -)"' >> ~/.bashrc
$ exec $SHELL -l

2. Checking our installation. Second command should give you a long list of PHP versions.
$ phpenv --version
rbenv 0.4.0-98-g13a474c

$ phpenv install -l

3. As I was running Debian, install all the necessary packages so we can compile the source code.
$ sudo apt-get install make ccache re2c libcurl libcurl-dev bison libcurl4-gnutls-dev libjpeg62-dev libmcrypt-dev libtidy libtidy-dev libxslt1-dev apache2-prefork-dev

4. Compilation. Took me around 15 minutes.
$ CFLAGS="-g" phpenv install 5.6.0

$ which php
/home/kianmeng/.phpenv/shims/php

5. Switching between installed version (system) and your compiled version.
$ phpenv versions
* system (set by /home/kianmeng/.phpenv/version)
5.6.0

$ phpenv global
system

$ php --version | grep ^PHP
PHP 5.4.4-14+deb7u14 (cli) (built: Aug 21 2014 08:36:44)

$ phpenv rehash
$ phpenv global 5.6.0

$ phpenv global
5.6.0

$ php --version | grep ^PHP
PHP 5.6.0 (cli) (built: Sep  1 2014 03:26:46)

Unfortunately, to install phpdbg, you'll need to create another shell script, as a plugin to php-build in order to build it. Someday perhaps.

PHP 5.6 New Features

It has been a while since I last code anything significant in PHP, but this 5.6 release do have quite a few significant features. Is this the final stable version before we all move to PHP 7?

The only feature I really like, the support of variable-length argument lists through variadic functions and argument unpacking. Example shown below.
function sum(...$numbers) {
    return array_sum($numbers);
}

$nums = [1, 2, 3, 4];
echo sum(1, 2, 3, 4), "\n"; // 10
echo sum(), "\n";           // 0
echo sum(...$nums), "\n";   // 10
echo sum($nums), "\n";      // 0

On additional changes to the namespaces. While the use operator currently support importing functions, constants, or classes, it still very much limited or rather half-baked when compare to Java or Python. For example we still can't use wildcards for mass import or shorter syntax in importing selected names as shown.
// no working.
use MyProject\Feature\*;
from FooLibrary use Foo, Bar, Baz;

Also, don't get me started on the whole backslash (\) as separator for namespace. I cringe every time thinking or looking at it. Sigh.

phpdbg, which is something new to me, was included and implemented as Server Application Programming Interface (SAPI) module. Unfortunately I can't get it to work, going to try it out in another post.

Note to self - 2014-06-19

I've a feeling that Vagrant and Google Chrome hates each other. I can understand Vagrant or Virtual Box is resource intensive but Chrome with just one tab with Gmail opened? Seriously?

The curse of PHP. Once you've been stereotyped as programmer of certain programming language, is hard to switch or move to another language.

Talking about being absent minded. Nearly lost my whole bag, didn't realized it until I traveled for hours.

Moving Away From PHP

This is probably the main reason why Perl was dethroned from its position as one of the leading programming language. Its role has been replaced by other more simpler programming language as in the web (PHP) and system admin (Python/Ruby). I was wondering, what will replace PHP, Python, or Ruby? Is PHP going to be replaced by Hack (by Facebook) or node.js or Python/Ruby being replaced by Golang?

Reflecting back my programming career. I made a mistake not moving away from PHP. I should have invested more times in other programming language like Java or Python, especially Java. Off course, mistakes were made and nothing much we can do beside accepting it and move ahead.

Is always good to try and learn different new technologies. Most importantly you must enjoy what you're doing and stay healthy to sustain it.

Note to self - 2014-06-05

1. Taobao, slowly but surely, will replace the local ecommerce players as the go to destination for online purchasing. Nothing interesting among them, just another reseller of items procured from merchants in Taobao. The real money or profit still flow through logistic, or to be specific, freight forwarder.

2. Watching items being purchased online in real-time was quite an additive activity. You will be surprised by the types of item purchased online and some of these items are dirt cheap! I'm so going to create a dashboard to load these purchases using my underutilized monitor.

3. What do you call a PHP programmer who are in the midst of switching to another programming language like Python? A better PHP programmer. Ouch.

4. PHP vs. Python. Python is a better when you want to learn more about programming in general or be a better developer. While PHP is great when you want to create something fast for the web. Contrary to popular belief, Python is not a beginner friendly language. By the way, PHP is a web template language. Which one makes you happy? Neither. But is good to finally escape from PHP after all these 10 years. For me, PHP is "cari makan" and Python is to stimulate my bored mind.

5. export PYTHONDONTWRITEBYTECODE=1
Yup. No more pyc files scatter around. Only for Python 2.6 though.

6. Read the bloody change logs. Seriously, when you're upgrading any software or libraries, please remember to read the bloody change logs.

7. Awareness, acceptance, and courage are the keys to become a better estimator. First, you must aware of your current situation. Second, you must accept the current limitation either in your or your surrounding. Third, you must have the courage to make hard decision and mistakes to go ahead.

PHP Successor?

"A lot of those "modern PHP" libraries are basically a masochistic exercise in copying designs that make sense in Java into PHP where they make no sense.

PHPT style tests wouldn't make sense in Java. And Java style Unit test frameworks make no sense in PHP.

However all those blindly supporting this, can please continue to waste their time, for the benefit of making sure they're buzzword compliant & in sync with groupthink."
-- mantrax [1], emphasis added

Sigh. My feeling exactly.

PHP the language has starting to show its age and limitation. From a template language, to a procedural scripting web language, and now a mutated siblings of Java-wannabe. Ironically, even Java web development itself is moving towards a scripting based language like Groovy.

I am hoping Facebook's HHVM will slowly replace PHP (Zend Engine), and, if possible, steer the direction of the language itself. Again, by replacing it with the Hack. They (Facebook) have all the resources to make this works.

Latest and Greatest or Just Stay Stagnate

"I don't actually agree with this. It's a cop-out. Some people will just say "Well, this procedural mess I've been copy-pasting since 1996 works for me, so I'll keep using that. Make an informed decision about what's the best option. That may or may not be to learn a new technology. But don't take "works for you" to mean you should not bother to progress in your learning. Too many PHP programmers sit back and stagnate."
-- mattaugamer
There is always an exception to any rules or advises given. It's considered a best modern practice to write you web application using a framework rather than flat PHP script. However, taking into consideration of the talent and time available, sadly you have to live with the flat PHP approach.

There is nothing wrong with that provided that you don't have to maintain the code base. If you're stuck maintaining the legacy stuff which will slowly hinder your learning progress, career advancement, and suffer the consequences of technical debts made by others, you're left with four choices. Put up and shut up, rewrite it using modern approach, delegate to another developer and never touch it again, or lastly just move on.

Legacy Code Base

Due to some unforeseen reason, I took a quick look over two legacy code base in the system to fix certain issues. The more I looked at it, the more my stress level shoot up. I literally want to strangle the original programmers or anyone near me.

Yes, the module or feature did almost work as intended but modification or bug fixing is a pain in the arse. I have to suppress my inner urge multiple times the whole day thinking of whether to do a total rewrite or refactor of the module. I kept shaking my head whether I should fix the bug first or refactor the damn module while fixing it.

Framework, especially Model-view-controller (MVC) framework provides a good initial structure for creating an application. At least, you have the advantage of separation of concerns (SoC) between all these three layers. However, problems arise when we're deciding on what or how to separate a program into these sections. I've seen many types of abuse of the MVC framework especially those lack of Object-Oriented (OO) mindset. While we have idiom like "Fat Models, Skinny Controller" exists as a guideline, it still, can lead to another form of abuse like God Models.

The lesson I've learned is that rather than taking the best engineering approach to design a system, instead use the most suitable solution understandable by the technical competency of the available programmers. You can't change a procedural to OO mindset as well as their egos instantly. Especially true for senior programmer as they said, old habits dies hard. If the basic understanding of MVC and OO is seriously lacking, might as well take what Ramus Lerdorf proposed "no-framework PHP MVC framework" approach. At least it is more procedural and understandable by most PHP programmer.

Modernize Your Legacy PHP Application

How? Code base restructuring. As suggested by the video presentation below, these are the recommended 2 steps.

1. Consolidate classes for autoloading.
Just implement autoloading according to PSR-0 specification. Move php script around and remove all the require or include statement. Do make sure is one class per file.

Also, group all your helper functions into classes and call these global functions through static or instance method. Example of static method.
xxx_get() to XXX::get()
xxx_set() to XXX:set()

Some of you may argue this does not bring any sort of benefits except more typing. I do agree as occasionally we sometimes have a few orphaned global functions which hard to be grouped in any class. Surely we're not going to put these helper functions in a class called Miscellaneous or Common class.

2. Convert global to injected dependencies
Those dreadful global variables (those using global keyword) which sometimes accidentally which values may reassigned half way through your script.

PHP 5.4 and MySQL 5.5 in CentOS 6.4

Due to some shenanigans in office, unfortunate miscommunication, and effing messed up provisioning, have to redo the LAMP installation again in CentOS 6.4. Installation steps as root shown below.

1. Install the Remi third party repository.
$ rpm -ivh http://rpms.famillecollet.com/enterprise/6/remi/x86_64/remi-release-6.4-1.el6.remi.noarch.rpm

2. Enable the Remi Repository and update.
$ vim /etc/yum.repos.d/remi.repo
$ yum update

3. Install the Apache Web Server, Mysql Database Server, and PHP. Configure and set the MySQL's password as well.
$ yum install httpd php php-mysql mysql-server
$ mysql_secure_installation

4. Enable both web and database server start upon reboot.
$ chkconfig httpd on
$ chkconfig mysql on
$ reboot