I think, therefore I am. I am, therefore I sail

Category: PHP Page 1 of 11

Quick tip to access protected properties in PHP object

Calling an object that has a protected property that you need access to? This function will allow you to quickly access data stored in protected properties of PHP objects.

Note: I tested this on PHP 7.4. It will likely work on other versions, but may need tweaking.

Good developers will protect the internals of their objects with private and protected scopes. That means from outside of the object your code will not be able to access whatever is protected. What I am about to show you breaks that encapsulation. Generally, this is not something you want to do, however, if you are working with an object you have no control over, it may be necessary. I ran across this while working with an object from an external library.

This method works by typecasting the object to an array. You can then access the property using a little known method.

Let’s see the code!

    function getProtectedValue( $object, $prop_name ) { 
        $array = ( array ) $object;
        $prefix = chr( 0 ) . '*' . chr( 0 );
        return $array[ $prefix . $prop_name ];
    } 

Photo courtesy of Unsplash https://unsplash.com/photos/Vp3oWLsPOss

Quick recursive PHP file syntax check

I find it handy to run a PHP syntax (lint) check on files after resolving a merge conflict in git.

Here is a handy snippet that will run find every file in the current and sub-directories and run them through the PHP command line syntax checker.

find . -iname "*.php" -exec php -l {} \; | grep -i "Errors.parsing"

Getting social media shares with php

Quick snippets to help me (and maybe you!) remember how to quickly and easily get share counts from social networks.

What other networks would you like to see?

Facebook

[php]
function facebook_share_count( $post_id ) {
$api = "https://graph.facebook.com/";

$url = $api . urlencode( get_permalink( $post_id ) );

$response = wp_remote_get( $url );
if( is_wp_error( $response ) ) {
return 0;
}
if( ‘200’ != wp_remote_retrieve_response_code( $response ) ) {
// Bad url
return 0;
}
$body = wp_remote_retrieve_body( $response );
$body = json_decode( $body );
if( isset( $body->shares ) ) {
// Shares will not be set if there are none!
return $body->shares;
}
return 0;
}
[/php]

Twitter

NOTE: ***Twitter will be shutting down this API*** No replacement has been announced.

[php]
function twitter_share_count( $post_id ) {
// Check for transient
if ( ! ( $count = get_transient( ‘twitter_count’ . $post_id ) ) ) {
// Do API call
$response = wp_remote_retrieve_body( wp_remote_get( ‘https://cdn.api.twitter.com/1/urls/count.json?url=’ . urlencode( get_permalink( $post_id ) ) ) );
// If error in API call, stop and don’t store transient
if ( is_wp_error( $response ) )
return ‘error’;
// Decode JSON
$json = json_decode( $response );
// Set total count
$count = absint( $json->count );
// Set transient to expire every 30 minutes
set_transient( ‘twitter_count’ . $post_id, absint( $count ), 30 * MINUTE_IN_SECONDS );
}
return absint( $count );
}
[/php]

LinkedIn

[php]
function linkedin_share_count( $post_id ) {
$api = ‘http://www.linkedin.com/countserv/count/share?format=json&url=’;
$api .= urlencode( get_permalink( $post_id ) );
if ( ! ( $count = get_transient( ‘linkedin_count’ . $post_id ) ) ) {
$response = wp_remote_get( $api );
if( is_wp_error( $response ) ) {
// eat it
return 0;
}
// Should verify the correct json is returned
$json = json_decode( wp_remote_retrieve_body( $response ) );
$count = (int) $json->count;
set_transient( ‘linkedin_count’ . $post_id, absint( $count ), 30 * MINUTE_IN_SECONDS );
}
return $count;
}
[/php]

Book Review: PHPUnit Essentials

In the past few years I have worked on many projects that involved implementing a testing infrastructure, I have spoken at conferences on the important of and theories of testing, and I have led workshops training beginners in testing. In all that time I have looked for a good concise and easy to read resource to share with people. PHPUnit Essentials by Zdenek Machek meets and exceeds my expectations.

Machek starts the book out by walking through the available installation methods and then moves into tools, in particular IDEs. Several popular open source and commercial IDEs are reviewed including: NetBeans, Zend Studio, Eclipse, and PhpStorm. Machek walks through the process of setting up PHPUnit in each IDE and running simple tests to get you started.

Machek goes into the basics of testing but the real power of this book lies in the thorough review of the more advanced testing concepts that many resources shy away from. Starting with theory on how to write good testable code all the way to testing databases, the following topics are covered: dependencies, in depth command line usage, test isolation, dealing with globals and data providers, test organization, test doubles (fakes, stubs, mocks, expectations, and proxies), database testing, API testing, and testing legacy (spaghetti) code. As a bonus Machek tossed in chapters on functional tests in the web browser, continuous integration, behavior-driven testing, and even a section on PHPUnit alternatives.

This is a small book but it is packed with a powerful amount of information and excellent code examples. It is a must have on any PHP developers bookshelf.

 

Legal Stuff

Disclosure of Material Connection: I received this book free from the publisher Packt Publishing. I was not required to write a positive review. The opinions I have expressed are my own.

If you would like me to review your book head over to the contact page and get a hold of me.

PHP: Erase a value out of an array without knowing its key

If you find yourself with an array that you know contains a certain value that you need to access or erase here is a useful code snippet that I came across the other day.

$key = array_search( $needle, $haystack );
unset( $haystack[$key] );

For example, given the following array:

$colors = array( 'red', 'blue', 'green', 'yellow' );

If you wanted to get rid of ‘green’ but are unsure of its key:

$key = array_search( 'green', $colors );
unset( $colors[$key] );

Or you could change it to ‘brown’ with:

$key = array_search( 'green', $colors );
$colors[$key] = 'brown';

Page 1 of 11

Powered by WordPress & Beards