Category: Recommendations

  • PHP 8.0 – 4 new features in this latest version

    PHP 8.0 – 4 new features in this latest version

    New PHP major versions are always very expected by PHP developers, we already know good things coming when a new release is announced. This time we have a lot of performance improvements and new features that improve our code, using modern programming methods in a badass old-school language.

    Besides those new features and recommendations, I strongly recommend we use them only for environments that we can expect and have sure that 8.0 is running. In some cases, we can use polyfills instead. If you’re a plugin developer, it’s too soon to start using the new features of this version.

    Nullsafe operator

    I really love clean and efficient code, so I’m not a fan of the classic if/else statements (why we shouldn’t use them? Read more here). However, there is always a time when we need to use a simple if/then, and the best way to do that is using an inline if statement Like this:

     $today_exists = time() ? true : false;

    Clean, useful and works like a charm. I can’t know how many times I’ve tried to check a null value of a class method (for example), giving a “then” statement in the same line. Simple – it wasn’t possible, and the solution was based into split the statement into two or more lines.

    The good news is called Nullsafe operator. PHP 8 now provides a null validation without any errors, so the following example now is pretty possible:

    $today_exists = $this->get_time()?->$this->is_true();

    str_contains() function

    With this new function, we no longer need to use the strpos() function. This last one is more recognized by developers to be used to verify if a string contains a word, like this:

    $today_exists = ( false !== strpos( 'Today is the day', 'Today' ) );

    Yes, that’s what we had to do to check if a string contains X word πŸ™‚

    Checking the documentation, it’s really strange to see str_contains() only is available from 8.0. In this link, you can also find a pollyfill alternative.

    New match() expression

    That’s a good one for clean code. Imagine we have a switch case expression, but optimized to be used without breaks, and organized as a class sintax. I’m particullary interested into starting to use this new approach, check some examples in the documentation.

    $food = 'cake';
    
    $return_value = match ($food) {
        'apple' => 'This food is an apple',
        'bar' => 'This food is a bar',
        'cake' => 'This food is a cake',
    };
    
    var_dump($return_value);

    Enums

    Exactly like other languages (e.g. javascript), enums provides us to call a function and have a definite number of cases on the args. The result is a more stable code. This one will be available in the 8.1 release only, but it’s a great example of what it’s happening with PHP – giving to the developers great native features we can use like a modern programming language.

    I’m looking forward to use these features on my code, and I’m confident that will be possible soon – PHP 8.0 has been launched in November 2020, so please read more about WordPress and 8.0 compatibility before starting to code.

  • MySQL and WordPress – How to use native queries in a secure and right way

    WordPress requires a MySQL instance to run and store all the data. Although the relational system is a classic and, sometimes, obsolete data structure, MySQL works like a charm on a WordPress environment.

    Keeping this on the WordPress core, gave us better compatibility with our custom development over time and quick and easy access to the data. However, rare times developers access the data using MySQL native queries – normally, the WP methods are enough for a straightforward development (New WP_Query, get_posts, etc…). But if you need deeper access to the data, SQL Queries need to enter on your WP package-skills. High-level SQL knowledge isn’t needed, but knowing some methods will be great for your future developments.

    Consider you already have some skills using SQL statements, I would like to show you the best secure way to work with it using WordPress Best Practices. Please follow me:

    WordPress Database Class

    WordPress core already has a class to interact with the database, it’s a global object: $wpdb. Don’t ignore it, this class is the safer and better way to access the database directly. If you need to extend the class for your specific needs, you can replace it in wp-content/db.php. Anyway, I strongly suggest only use this alternative if the existing methods don’t be enough.

    Sanitize and Escape everything

    2021 and SQL injection still exists. Using $wpdb, we just need to use the “prepare” method to prevent possible SQL attacks.

    $sql = $wpdb->prepare( 'SELECT * from %s' , $table_name );

    Pretty simple and supports placeholders! After sanitizing and escaping our SQL query, we’re able to run the query.

    Query Methods

    I recommend you three main methods to run queries, depending on what you need to do with the data: consult, write, delete…

    1. get_results()
      One of my favourites, this function is used for getting an array with query results. Perfect for “SELECT” statements.
    2. get_var()
      Same as get_results(), but better for receiving a single value – a custom meta, for example. The returned value is a string, instead of an array.
    3. query()
      Use this when you need to write on the database. The function will return a true/false.

    A Complete Example

    Imagine you want to list all the WP users on an array. The best way to do that is:

    // first, call the object to be accessible
    global $wpdb;
    
    // don't forget to use the ->prefix for a dynamic table name
    $users_table = $wpdb->prefix . 'users';
    
    // your safe query
    $query      = $wpdb->prepare( 'SELECT * FROM %s', $users_table );
    $users_list = $wpdb->get_results( $query );
    

    That’s it. I recommend you read more about the $wpdb object and be prepared to write safer and more performative SQL queries on WP. Use the comments box for additional questions or suggestions!

  • An important recommendation about Web: designed to last

    The Development of the Web keeps changing, and at this time seems like the fashion industry: trends come and go. Today I read that post designed to last and I’m writing just to recommend you this lecture:

    https://jeffhuang.com/designed_to_last/