Search code examples
phpexpressionengineuid

How do I generate a unique ID in Expression Engine 2?


Is there an EE2 tag that produces a unique ID? Or would I need to embed a PHP uniqid() call to get the desired unique ID? Thanks.


Solution

  • No, there is not a EE tag that does that. It would require that you created your own plugin, extension or module. But that pretty simple.

    My suggestion is to create a plugin.

    Create a folder named guid in your expressionengine/third_party folder.
    In that folder, create a file called pi.guid.php with the following content:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    $plugin_info = array(
        'pi_name'       => 'Uniqid',
        'pi_version'        => '0.1',
        'pi_author'     => 'John Doe',
        'pi_author_url'     => 'http://example.org/',
        'pi_description'    => 'Returns uniqid() with parameters',
        'pi_usage'      => Guid::usage()
    );
    
    
    class Guid {
                
        public function __construct()
        {
            $this->EE =& get_instance();
        }
        
        public function uniqid()
        {
            $prefix = $this->EE->TMPL->fetch_param('prefix');
            $more_entropy = (strtolower($this->EE->TMPL->fetch_param('more_entropy')) == "true") ? TRUE : FALSE;
            
            return uniqid($prefix, $more_entropy);
        }
        
        public static function usage()
        {
            ob_start();  ?>
    
            Simple use:
    
        {exp:guid:uniqid}
    
            Parameter use:
    
        {exp:guid:uniqid prefix="yourprefix"}
        {exp:guid:uniqid more_entropy="true"}
        {exp:guid:uniqid prefix="yourprefix" more_entropy="true"}
        <?php
            $buffer = ob_get_contents();
            ob_end_clean();
    
            return $buffer;
        }    
    }
    

    There you go, your very own plugin to create uniqid() through tags.
    The use?

    {exp:guid:uniqid prefix="yourprefix"}
    {exp:guid:uniqid more_entropy="true"}
    {exp:guid:uniqid prefix="yourprefix" more_entropy="true"}
    

    Awesome, right?
    I love EE...