Dependency Injection is a software design pattern that allows avoiding hard-coding dependencies and makes possible to change the dependencies both at runtime and compile time. By using Dependency Injection we can write more maintainable, testable, and modular code. All projects have dependencies. The larger the project the more dependencies is it bound to have; now having a great… Read More
You know how Dribbble shows a color palette for each shot users upload? They always look perfect right? Here’s a tool that can give you the same quality results using pure JavaScript. I played with Color Thief a few months ago but surprisingly never posted about it. For me, something that’s easy to use and has consistently great… Read More
Have you ever needed to send a PHP variable, array, or object to JavaScript? It can get complicated trying to escape the output properly. Here’s a way that always works—no escaping necessary. Let’s say we have the following variable in PHP:
1 |
$name = 'Bob Marley'; |
And we want to pass it to a JavaScript variable called name. Here’s the… Read More
Managing a RESTful application in PHP can become a headache if you are new to REST but I have developed a reusable class function that will save you hours of development time shown below. Feel free to reuse it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?php protected function returnRestfulValues($data) { if ($this->method == 'GET') { // find values in the url in fixed positions. ie: example/verb/123/456 return "SUCCESS: You performed a GET request using verb '" . $this->verb . "' with args " . $this->args[0]; } elseif ($this->method == 'POST' ) { // find values in POST request body. return $this->request; } elseif ($this->method == 'PUT') { // important! form 'enctype' should be: "x-www-form-urlencoded". // put url-encoded data contained in the request body into an array. // (ie: key/values from PUT request body (ie: "username=bob&password=willowtree") parse_str($this->file, $data); // http://php.net/manual/en/function.parse-str.php $url_values = $this->args; // (ie: the record ID to update) return $data; } elseif ($this->method == 'DELETE') { // works just like GET other than the HTTP verb DELETE return $this->args; } else { return "Whoops! you're not doing it correctly."; } } ?> |
Sometimes you might need to create a variable in PHP having the name of some value. Below is the easiest way to accomplish this need.
1 2 3 4 |
<?php // wrapping a variable with {} will concate the string into a variable. ${$variable} = $variable; ?> |
Using PHP shorthand IF/Else statements are a great time saver and help make your code look neater. Here is a collection of examples I often use.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
Basic True / False Declaration $is_admin = ($user['permissions'] == 'admin' ? true : false); Conditional Welcome Message echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!'; Conditional Items Message echo 'Your cart contains '.$num_items.' item'.($num_items != 1 ? 's' : '').'.'; Conditional Error Reporting Level error_reporting($WEBSITE_IS_LIVE ? 0 : E_STRICT); Conditional Basepath echo '<base href="http'.($PAGE_IS_SECURE ? 's' : '').'://mydomain.com" />'; Nested PHP Shorthand echo 'Your score is: '.($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average') ); Leap Year Check $is_leap_year = ((($year % 4) == 0) && ((($year % 100) != 0) || (($year %400) == 0))); Conditional PHP Redirect header('Location: '.($valid_login ? '/members/index.php' : 'login.php?errors=1')); exit(); |
When you export JSON form PHPwhich contains data from an “unclean” data source you must enforce UTF-8 upon the data that will be added into your JSON structure. Below I’ll show an example of exporting JSON and enforcing UTF-8 upon each record data entity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php /* Let's assume I pulled all jobs from some database here */ $jobs = Jobs::getAll(); // Convert this array of objects into an assoc array. $json = []; foreach ($jobs as $job) { // must enforce utf-8 onto all field data to insure json_encode() is not violated. $rec = (array)$item; foreach ($rec as $key => $val) { $rec[$key] = utf8_encode($val); } /* Repack the array assigning the record's jobid as the JSON record id */ $json[$item->jobid] = $rec; // faster than array_push(arr, val); } /* Output JSON. Don't forget proper header. */ header('Content-Type: application/json'); echo json_encode($json); ?> |
Sometimes you need to export a collection of data for use to another system. One of the easiest ways is to export it to XML as it is widely accepted as a data exchange format and standard. PHP makes creating and exporting to XML very easy. Below I’ll show you an example where I am exporting… Read More
I had to process a lot of Word .docx files into readable content for use in a searchable database. Docx files are basically xml files in a zipfile container (as described by wikipedia). Here is my solution, it’s pretty straight forward. Just pass in the server file path to the read_docx() function and it will… Read More
Validating Email Addresses is one of the more elusive patterns to define, but this pattern will match 99.99% of all email addresses in actual use today.
1 |
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])? |
A further change you could make is to allow any two-letter country code top level domain and only specific generic top level domains. This regex filters dummy email addresses… Read More