in Back to PHP

My Way to PHP: Day 2 of 75

Second day. I woke up early today which is a good sign – I still have the a lot of motivation in me to learn more. I’ve just posted the first day of my journey

I just started reading the chapter about databases. The current page is 207. My goal will still be 50 pages which would be the start of the chapter about PDFs.

Let’s go:


PDO has an execute and prepare function. I quite like the syntax of the placeholders. Example:

$statement = $db->prepare("INSERT INTO cars (modelno, type, price) VALUES" 
                          . "(:modelno, :type, :price)");
    
$statement->execute(array(
    'modelno' => 2835,
    'type' => 8,
    'price' => 23000));

Transaction support is also included. Example of a try ... catch with transactions:

try {
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->beginTransaction();
    
    $db->exec(...); // do all the transactional stuff
    
    $db->commit;
} 
catch (Exeception $error) {
    $db->rollback();
    echo "Transaction aborted {$error->getMessage()}";
}

The chapter about graphics. I remember generating graphics for all kind of different things. Mostly however to implement as a signature – your name, your rank, some picture. This was RADICAL back then :P.


I’m quite pleased about the chapter about security. It captures the most important attacks. I also learned about session_regenerate_id() which creates a new session id (either URL or cookie) and umask() to create a file with the correct permission.

Edit: Interesting enough in the appendix they recommend chmod() when using a multithreaded webserver – that is, pretty much always. Strange.


The output buffering can use ob_start() which takes one parameter a callback. Basically you can create all your content and then write a callback function which edits your output again. Quite interesting.

You can also use it for compression (or encryption theoretically).


Customer error handler with set_error_handler(). Great for frameworks you can run in different modes. E.g. in dev mode all errors are displayed to the browser but in production mode all errors are logged into a file.

error_log() provides the base for that. You can either log the error or even send it by e-mail – which is pretty nice!

And I just read that that is basically build in into PHP. If you go into production, you can set the php.ini to:

 display_errors = Off
    log_errors = On
    error_log = /foo/bar/errors.log

A section on performance tuning. Pretty cool. I also like the introduction which focuses on the futility of a lot of premature optimizations. I think the old philosophy of Make it work, make it right, make it fast still applies today.


The bit about interfacing with COM is neat. I’ve never written code interfacing with COM but I can see use it in – especially if your product is for internal use in an office.


There are functions to interface with JSON. You can also take the JsonSerializable interface and implement it with your classes using the method jsonSerialize(). Otherwise it just returns an associative array with all the fields of the class.


Also pretty nice that the book explains the different stages: dev / staging / production. I like it because even new programmers have the chance to be subject to these ideas and hopefully some will adopt them.


DateTime class for all date handling. The design looks good. Times zone handling and diff is build in.


Now I’m reading through the appendix which covers all build-in functions (without modules).

The first cool one is array_combine(). Which takes two arrays, one for keys and one for values. Pretty useful!

var_dump(array_combine(array("Name", "Age", "Location"), array("Peter", 27, "USA")));

/* 
array(3) {
  ["Name"]=>
  string(5) "Peter"
  ["Age"]=>
  int(27)
  ["Location"]=>
  string(3) "USA"
}
*/

array_count_values() returns a frequency distribution of an array:

var_dump(array_count_values(array(3, 4, 1, 2, 3, 3, 4, 0, 3)));

/*
array(5) {
  [3]=>
  int(4)
  [4]=>
  int(2)
  [1]=>
  int(1)
  [2]=>
  int(1)
  [0]=>
  int(1)
} */

array_filter is just the usual filter function but it keeps the keys.

var_dump(array_filter(range(1,5), function ($x) {return ($x > 2); }));

/* 
array(3) {
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
} */

array_map is a usual mapping function. One main difference to other languages is that it will use the full length of all array arguments and just pad the other one instead of exiting early.

var_dump(array_map(function ($x) { return $x * 2; }, range(1,5)));

/* array(5) {
  [0]=>
  int(2)
  [1]=>
  int(4)
  [2]=>
  int(6)
  [3]=>
  int(8)
  [4]=>
  int(10)
} */

var_dump(array_map(function ($x, $y) { return ($x * $y); }, range(1,20), range(1,5) ));

/* array(5) {
  [0]=>
  int(1)
  [1]=>
  int(4)
  [2]=>
  int(9)
  [3]=>
  int(16)
  [4]=>
  int(25)
} */

call_user_func_array takes a function name and an array and applies it. Similar to apply. You can also use an anonymous function as the first parameter!

function product($a, $b, $c) {
    return $a * $b * $c;
}

var_dump(call_user_func_array('product', array(1,2,3)));

fgetcsv is in the standard lib. I don’t know how good it is but it’s there! And there’s fputcsv for writing csv files.


There are some interesting functions in there. e.h. hypot who calculates the hypotenuse of a right-angled triangle. Or there are time functions which return when the sun rises or sets.


Done! I read the complete book :). I think it was quite solid. There were some discrepancies and typos but overall solid book and it perfectly fit my requirements! And onwards we go!


Next I wanted to read Expert PHP and MySQL Application Design and Development. Let’s see how good it is.

The intro is super interesting. It seems a bit like a printed apprenticeship. Less ‘syntax here and there’ and more ‘here’s how we work’. Exciting!

The implication is that the success of your application development is entirely determined by whether people are satisfied with it. […] Even if your database is in 3NF, your PHP is OO, your HTML uses CSS to separate form from function, you use the latest Agile processes, and you’ve chased down all the bugs, it won’t matter if the people for whom you built the system aren’t satisfied with it.

Beautiful quote. I like how it expands the view of the people. It’s not just direct users, its the stakeholders, too. Try to maximize the happiness but prioritize. Normally, the most important stakeholder is the person who pays you. The rest depends on the circumstances.

I have to say that I love the war stories. I loved them in Skiena’s book and reading edw519’s comments and reading Dreaming in Code. I wonder if there are more books like that.


I like the idea of a prototype and production phase for new kinds of software. The idea is that if you have to plan the development of some kind of innovation start with the prototype first. Present it to the customer and then do the scheduling.


Interfaces that only communicate with the database are easier to manage.

I was pretty much always inclined to work with the database and let it do as much as possible. I find it cleaner and less complex. It’s good to hear that I’m not the only one.

I think I’ve written about this before but I love the UNIX philosophy of everything is a file. A database is kind of a file but it’s decoupled from the language or tool. That is, you can write your frontend in PHP, your scheduling algorithm in Python, your optimizations in C and it’s no problem because there’s this beautiful thing called a file or database which connects without problem to any of them. Or even better, you don’t have to write much code because you can use existing software!


[…] the team will have to keep track of changes to requirements, bugs found in testing, design questions to be resolved, assorted things-to-do, and the like. I call them all issues and enter them into a database so they won’t be forgotten.

[…] What system you use isn’t as important as that you use it for all issues, so there’s only one place to look. E-mails, scraps of paper, text messages, and oral comments should all be entered into the issues tracker.


Requirements should include (specifically for typical PHP/MySQL projects):

  1. Database and it’s main entities
  2. CRUD
  3. Processing (everything more complicated)
  4. Reports
  5. External interfaces
  6. I18N and L10N
  7. Accessibility
  8. User admin (logins / rights)
  9. Billing
  10. Browsers and platforms
  11. Installation
  12. Capacity
  13. Documentation
  14. Training
  15. Support and maintenance
  16. Conversion (from other systems / databases / etc.)
  17. Use cases

MySQL Workbench looks nice I’m definitely going to check that one out!


I found designing databases not that of a hard task – however I’ve never designed gigantic ones.

Here are the four steps from Peter Chen’s The Entity-Relationship Model:

  1. identify the entity set and the relationship sets of interesting
  2. identify semantic information in the relationship sets such as whether a certain relationship set is a 1:n mapping
  3. define the value sets and attributes
  4. organize data into entity/relationship relations and decide primary keys

That’s a great tip for attributes.

If there’s a standard use it

E.g. postal addresses!


In a section about constraints I learned that MySQL (and MariaDB) don’t support check constraints. Really surprising, considering that SQLite even supports them.


generatedata.com is a pretty useful site for generating example data. Check it out!


Super nice, even talks about two-factor authentication!


What I really liked was an application he developed which allowed users to do simple SQL queries, run them and save them. Super nice!

(the access was of course restricted)


The whole chapter data conversion reminds me of a lot of work I’ve done in the past. Old databases which aren’t really supported without any documentation. Inconsistent naming and dates. Errors over time or data just on paper. But somehow I still found it pretty fun! :D


I’m done! I really liked this book because it was so different and so real. It wasn’t the typical theoretical book but rather here’s what I’ve done. I liked the war stories sprinkled in. I’m also impressed that he published basically his own framework. I knew quite some stuff either because I just read Programming PHP or by books I read before or just by experience. But if you’re new that’s an invaluable book!


I wonder which book I should read next. I have two candidates which both are more on the OOP side which I still lack depth in. I think I’m going with a bit of a controversial one judging by the amazon reviews. If it is too bad I just take a look at the other one.

Hereby I start reading Learning PHP Design Patterns.

In no small measure, this book is for those who felt a certain delight when programming was new to them. This is for the developer who thought nothing of working on a program all night long just because it was interesting, staggering off to bed, only to start on another program as soon as he woke up.

That was pretty much me. I’m intrigued


My first was Fortran II in college, then on to Basic, FORTH, PostScript, and then into assembly and machine language. I was more interested in learning about different languages than I was in good programming.

Could have described me. I started off with Pascal (not much), then to PHP, C, Perl, C++, assembly, Python, Javascript, Haskell, Common Lisp, Scheme and Clojure.

I’ve written most of my code probably in Python, Javascript and PHP. And now, like you probably have guessed I try to get my PHP up to date.

However, I actually learned OOP in school. Still didn’t use it much in my private projects. And in the cases I used it the design were pretty simple I can’t remember using inheritance once when writing my own classes. Yep.


Single Responsibility Principle = a class should only have one responsibility


Once a big complex problem has been modularized into solvable subproblems (interfaces / classes), encapsulation is a way of taking the smaller abstractions and compartmentalizing them.

Interesting way to look at design. First we start think about solvable subproblems and afterwards we take a look at the classes and implementations.


On inheritance: The author also recommends do keep inheritance swallow and often just interfaces.

Also a side note: Most of the OOP stuff I read uses examples like the shape example or animals. I think they hurt OOP. Use stuff people solve in real life instead of some artificial problems.


The day is over. I’m quite pleased with my progress. While learning the last two days I was quickly comfortable in PHP again. It will take me some time to get as good as I’m in Python – probably around two years. But I’m on my way.

Updated Goals (19th October)

  • Relearn the basic syntax, keywords, constructs
  • Learn the intricacies: how does the interpreter work, the OOP system, etc.
  • Get a overview over the standard library
  • Learn the right and idiomatic way to do PHP development today
  • Learn the most important pitfalls
  • Learn a bit more about MySQL
  • Learn more about the PHP OOP and Design Patterns
  • Learn Symfony2
  • Write at least one web app using Symfony2 and its core components (templating, testing, forms, validation, security, caching, i18n)
  • Learn all the array functions
  • Learn about functional programming in PHP
  • Read Patterns of Enterprise Application Architecture

Progress status

Done

  • Relearn the basic syntax, keywords, constructs
  • Learn all the array functions
  • Read Programming PHP by Kevin Tatroe, Peter MacIntyre, Rasmus Lerdorf [done]
  • Read Expert PHP and MySQL Application by Marc Rochkind [done]

In Progress

  • Learning PHP Design Patterns by William Sanders [41 of 362 pages]

Write a Comment

Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Webmentions

  • My Way to PHP: Day 6 of 75 – panictank

    […] Yep. I’ve written about that, from Day 2: […]

  • My Way to PHP: Day 3 of 75 – panictank

    […] again I woke up early! I just spend about half an hour editing todays post (that is yesterday when you read this). Now I’m looking for more resources especially about […]