Blog

using composer in wordpress plugin development

using composer in wordpress plugin development

Why Composer is important

Composer is a dependency manager for PHP , and here very practical explain why is important .

If you were to start manually picking the bits you wanted from Zend, or Laravel orSymfony, then it would become very difficult to manage. Each library might also have dependencies, and so you would end up in a mess, particularly if you required other people to work on your project. culttt

Using Composer inside WordPress Plugin

if you want to know how create plugin you can read our previously post , we will start here by create composer.json file in the plugin root directory and write in it our required packages .


{ 
    "require": { 
        "nesbot/carbon": "^1.20" 
    } 
}

as example I use Carbon , carbon is a simple API extension for DateTime. After add this package to our composer file we need to install it from shell


composer install

let’s load packages in plugin code


add_action('admin_menu', 'my_plugin_menu'); 
function my_plugin_menu() 
{ 
	add_menu_page('My Plugin Settings', 'Plugin Settings', 'administrator', 'my-plugin-settings', 'my_plugin_settings_page', 'dashicons-admin-generic'); 
	 
} 
function my_plugin_settings_page() 
	{ 
	require_once(plugin_dir_path(__FILE__).'vendor/autoload.php'); 
	// 
	require_once(plugin_dir_path(__FILE__).'views/time.php'); 
	}

view file will look like this :


<div class="wrap"> 
<h2>Using Composer </h2> 
<?php 
use Carbon\Carbon; 
printf("Right now is %s", Carbon::now()->toDateTimeString()); ?> 
</div> 

composer-wordpress-1
you can use many useful packages from composer in your plugin just by search at https://packagist.org