Category Archives: Code

Enhancing Your Toolset with Modern PHP Features

In the ever-evolving landscape of web development, staying adaptable is key to delivering efficient and innovative solutions. This blog explores how embracing modern PHP features can enhance your coding experience, making your work not only effective but also enjoyable.

1. First-Class Callables in PHP (PHP 7.4 & Up)

One of the most significant advancements in PHP has been the introduction of first-class callables, which treat functions as first-class citizens—meaning they can be assigned to variables, passed as arguments, and stored in arrays. This flexibility allows for dynamic and versatile code execution.

Example:

// Define a function dynamically:
function myFunc($num) {
    return $num + 5;
}

callables[] = 'myFunc';

$result = callables[0](10); // Outputs: 15

By treating functions as first-class citizens, you can easily switch between different operations or even replace built-in functions with custom ones, enhancing the dynamic nature of your applications.

2. Closures as First-Class Callables (PHP 8.0 & Up)

Starting from PHP 8.0, closures have been elevated to the status of first-class callables. This means they can be manipulated and treated just like any other callable type, adding another layer of flexibility to your code.

Example:

function createClosure() {
    return function ($a) use ($b) { // $b is not used here.
        return $a * $b;
    };
}

$closure = createClosure();
$firstClassCall = new \Closure($closure);

$result = $firstClassCall(4, 2); // Outputs: 8

This feature allows for more dynamic and reusable code structures, making your applications both powerful and elegant.

3. Named Arguments in PHP (PHP 8.3)

Introducing named arguments in PHP 8.3 is a significant enhancement that simplifies function calls by allowing parameters to be passed by name instead of position. This not only reduces errors but also improves code readability, especially when dealing with functions or methods that have numerous parameters.

Example:

function greet($name, $message = 'World') {
    echo "$name, $message!";
}

greet('Alice', 'From'); // Outputs: Alice, From!

Named arguments make your code cleaner and more maintainable, as they eliminate the need to remember parameter order when calling functions.

4. Async Functions & Generators with await (PHP 8.2)

With the introduction of async/await syntax in PHP 8.2, handling asynchronous operations has become more intuitive and less error-prone. This feature simplifies working with native closures and generators, making your code easier to read and maintain.

Example:

<?php

namespace App\Services;

function processRequest($request) {
    // Simulate delay
    sleep(0.5);

    return $request->id;
}

async function processRequests() uses [processRequest] {
    yield 'Processing request 1';
    yield 'Request 2 pending';
    try {
        yield 'Request processing...';
        yield processRequest('Some Request');
    } catch (\Exception $e) {
        yield 'Error: ' . $e->getMessage();
    }
}

$result = await processRequests();

// Collect results if needed.

Async/await syntax enhances the manageability of asynchronous tasks, making your code more efficient and scalable.

5. Attributes in PHP (PHP 8.0 & Up)

Attributes are annotations that can be used to add metadata to classes or functions. Introduced in PHP 8.0, they provide a concise way to include information such as SEO tags, styling instructions, or other metadata without duplicating code.

Example:

<?php

namespace App\Enums;

attribute('description' => 'Intelligent Enumerator')
interface EnumeratorInterface {
    use Closure;

    function enumerate($value);
}

enum MyEnum: EnumeratorInterface {
    #[EnumeratorValue('A')]
    const A = 1;
    #[EnumeratorValue('B')]
    const B = 2;

    public function enumerate($value) {
        if (in_array($this->value, [$value])) {
            return $this->value;
        }

        // Additional logic...
        return parent::enumerate($value);
    }
}

// Usage
$enumerator = new MyEnum('B');
echo $enumerator->enumerate(3); // Outputs: B

By leveraging attributes, you can enhance your code’s metadata capabilities, making it easier to maintain and SEO-friendly.

Conclusion

Incorporating modern PHP features like first-class callables, closures as first-class callables, named arguments, async functions with await syntax, and attributes can significantly enhance the quality and maintainability of your web applications. Embracing these tools allows you to write more dynamic, efficient, and readable code, setting your project apart in a competitive landscape.

By staying open-minded and continuously learning new techniques, you not only improve your coding skills but also stay ahead of potential challenges, ensuring your projects remain robust and scalable. Happy coding!

Hubspot Embedded Form onFormReady & onFormSubmit

Hubspot is a fantastic tool for enabling custom forms on your website and saving that data into the Hubspot CRM for later actions. When using forms embedded on non-Hubspot websites I often find myself needing to stretch outside the scope of the default for the embed.

The Code

The code below you will see a few handy additions to the Hubspot form embed; onFormReady and onFormSubmit.

hbspt.forms.create({
     portalId: "xxxxxxx",
     formId: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx",
     css: "",
     onFormReady: function($form){
        // Stuff to do on after form is loaded             
     },
     onFormSubmit: function($form) {
        // Stuff do do before form is submitted 
     }
   }
});

On an embedded form, Hubspot dynamically loads some javascript and pulls in additional field data asynchronously after the page is loaded. If you need to add any manipulation to the load form or fields, you should do this in the onFormReady function.

Although documented in Hubspot’s documentation, if you are manipulating field .val() using jQuery there is a gotch that requires the addition of the .change() function.

jQuery('textarea[name="additional_order_comments"]').val('').change();

Without the above .change() function, Hubspot would submit the previous value of the field if was previously set and your CRM is set to pre-fill the fields.

The Issue

I had the need to create a form that used progressive fields, but also allowed me to present a comment form field that did not pre-fill the text area. As of this blog post, Hubspot does not include any option to turn off previous form values when using progressive fields.

The website needed to provide a field for additional comments and did not want to write an blank value for the field if it contained an existing value. So with some simple jQuery magic, the form now stores the form fields value, removes the field value on the form field, then re-applies the old value unless a new text value is entered.

hbspt.forms.create({
     portalId: "xxxxxxx",
     formId: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx",
     css: "",
     onFormReady: function($form){
        textareaDefault =  jQuery('textarea[name="additional_order_comments"]').val();
jQuery('textarea[name="additional_order_comments"]').val('').change();                   
     },
     onFormSubmit: function($form) {
if(jQuery('textarea[name="additional_order_comments"]').val().length < 1){            jQuery('textarea[name="additional_order_comments"]').val(textareaDefault).change()
      }
   }
});

As mentioned previously, you will see the requirement for the .change() function in the jQuery selector above.

If this article helped you out, please leave a comment below, I always enjoying knowing I have helped others along their coding endeavors!

Channel Images Converter for Expression Engine

I am a pretty big proponent for many of DevDemon’s addons. But without a doubt, Channel Images is at the top of the list. The ease of use for me as the developer and the for the client is immeasurable and well worth the cost of the addon.

As fantastic as the plugin is, there are a few downfalls, Like trying to get data into Channel Forms. The one that faced me this week was bulk importing images to the Channel Images field.  As of this post, this is not a default functionality in Channel Images or any of the importer plugins available.

After some research I was able to find a plugin that Yuri Salimovskiy of IntoEEtive posted in replies on a forum that would take native File field attachments and import them into Channel Images. So I quickly downloaded the plugin, backed up my database, then ran the plugin.  I activated the “Channel Images Converter” and I crossed my fingers.

Unfortunately it didn’t work 🙁

I shot a quick message over to Yuri to see if there was an updated version available, however there wasn’t, but he did give me a few pointers and a few messages later I was able to update the addon to be compatible with ExpressionEngine 2.9.2.

Continue reading

Semantic-UI: The Best of Both Worlds

Starting a new project is fun, starting a new project with the best/new technology available is even more exciting.  There are many popular UI/Responsive frameworks available. The top two at this this time are Twitter’s Bootstrap and Zurb’s Foundation. Each of these frameworks are on multiple revisions and are used heavily on the web.

Bootstrap

I have used bootstrap for quite a few projects, it’s a great framework with a HUGE community.  Bootstrap does a phenomenal job of including as many ui elements styled to match seamlessly with each other and themes abound all over the web. The way bootstrap handles it’s grid system is familiar and easy, but I am not a fan of how it handles the responsive resizing of grids and elements. Bootstraps approach to responsive columns is to add media queries to handle smaller screen sizes. While this works, and most people won’t notice, it does add additional overhead and load for mobile devices.

Another factor for me looking into another alternative to bootstrap is the fact that bootstrap sites look and behave like bootstrap. 95% of the site that use bootstrap are easily identifiable as bootstrap.  Check out the bootstrap sponsored expo gallery to see what I mean.

allthesame

Don’t get me wrong, I am not saying anything negative about the above sites. These sites all have good design, and they are well done.

Continue reading