Search code examples
phpnamespacesprestashopprestashop-1.6prestashop-1.7

Using namespaces in Prestashop module


How we can make the Prestashop module compatible with version 1.6 that uses namespaces, As I'm looking into the Prestashop documentation which says PrestaShop 1.6 does not fully support namespaces. They throw some issues when used in specific places. Is there any alternative way to this? Ref: https://devdocs.prestashop.com/1.7/modules/core-updates/1.6/


Solution

  • You don't need to use namespace or "use" word for the main file.

    I think you can use just full name in you code for example:

    $data = \PrestaShop\Some\ClassName::getData();
    

    or if you want to use namespace as you want. you can make an empty class for the main file and make a class with your namespace for the parent.

    so we have modules/yourmodule/yourmodule.php as the main file

    <?php
    
    if (!defined('_PS_VERSION_')) {
        exit;
    }
    
    require_once(dirname(__FILE__) .'/classes/yourmoduleparent.php');
    
    class YourModule extends \YourModule\Bootstrap {
        
        // The module codes have been transferred
        // to the "/classes/yourmoduleparent.php" file.  
        
    }
    

    in modules/yourmodule/classes/yourmoduleparent.php

    <?php
    
    namespace YourModule;
    
    if (!defined('_PS_VERSION_')) {
        exit;
    }
    
    use Module;
    use Configuration;
    use Context;
    use Tools;
    use Controller;
    use PrestaShopException;
    use Hook;
    
    class Bootstrap extends Module {
        
        // Your module codes
        
    }