Skip to content
objectivehtml edited this page Dec 22, 2014 · 36 revisions

Overview

Developers can take complete control of Postmaster and harness the power of its underlying API's. The following are the API's current available to developers.

  1. ParcelType API
  2. ParcelSchedule API
  3. NotificationType API
  4. NotificationSchedule API
  5. Service API
  6. Events

Registering Classes

Postmaster allows developers to extend the core classes within their own plugins. When Postmaster is updated, your classes will never be overwritten. Before you can use your new classes in Postmaster you must register them so they will be recognized in the control panel. Once you register your classes, they will be available for immediate use. It's best practice to register your classes in the MyFooPlugin::init() method after the postmaster.onInit callback has been triggered.

public function init()
{
	craft()->on('postmaster.init', function(Event $event)
	{
		// First require your class if it's not auto-loaded by PHP
		// Obviously if you are loading multiple files that aren't auto-loaded,
		// you need to require all them, not just one.

		require_once('YourFileName.php');

		// Register multiple parcels types at once
		craft()->postmaster->registerParcelTypes(array(
		    'Craft\FooParcelType',
		    'Craft\YourParcelType',
		));

		// One parcel type at a time
		craft()->postmaster->registerParcelType('Craft\FooParcelType');

		// Register your parcel schedules
		craft()->postmaster->registerParcelSchedules(array(
		    'Craft\FooParcelSchedule'
		));

		// Register your notification types
		craft()->postmaster->registerNotificationTypes(array(
		    'Craft\FooNotificationType'
		));

		// Register your notification schedules
		craft()->postmaster->registerNotificationSchedules(array(
		    'Craft\FooNotificationSchedule'
		));

		// Register services
		craft()->postmaster->registerServices(array(
		    'Craft\FooService',
		    'Craft\YourService',
		));
	});
}

ParcelType API

ParcelTypes allow you to create different types of parcels that do different things beyond the default. These parcels can fire at anytime and can perform any arbitrary code you need. The great thing about creating your own ParcelType compared to rolling your own solution is that that you inherent all the services provided by Postmaster. For instances, you can can create your own interface, settings, and event binding logic, then pass all that to whatever service the user chooses. It's extremely fast to create custom notifications using ParcelTypes.

<?php
namespace Craft;

use Craft\Craft;
use Craft\Plugins\Postmaster\Components\BaseParcelType;

class MyParcelType extends BaseParcelType {
	
	// The name of your service and how it will appear in the app
	public function getName()
	{
		return Craft::t('My Parcel Type');
	}

	// A unique camelCased string used programmatically in the app
	public function getName()
	{
		return 'myParcelType';
	}

	// Do something at the start
	public function init()
	{
		// Set some stuff since we can't use "$this" in callback in PHP 5.3, super lame
		$parcelType = $this

		// Bind the event, this is any event (or events) you want
		$this->craft()->on('some.event', function(Event $event) use ($parcelType)
        {
        	$parcelType->parcel->parse(array(
        		'varName' => 'Some Value',
        		'varName2' => 'Some Value'
        	));

         	// Super simple, just create a Postmaster_TransportModel and give
         	// it a service, some settings, and some data for later use (by a service maybe).
            $obj = new Postmaster_TransportModel(array(
                'service' => $parcelType->parcel->service,
                'settings' => $parcelType->settings,
                'data' => array()
            ));

            // Send Postmaster_TransportModel to the parcel and let the API's
            // do the wrest... 
           	$parcel->send($obj);
        }
	}

	public function onBeforeSend(Postmaster_TransportModel $model)
	{
		// If you return false, the parcel will not be sent
		return true;
	}

	public function onAfterSend(Postmaster_TransportResponseModel $model)
	{
		// Do something after the parcel has been sent

		return;
	}

	// Get your input fields html (appears in the Parcel tab)
	public function getInputHtml(Array $data = array())
	{
		return $this->craft()->templates->render('myplugin/myParcelType/fields', $data);	
	}

	// Gets your settings html (appears in the Settings tab)
	public function getSettingsInputHtml(Array $data = array())
	{
		return $this->craft()->templates->render('myplugin/myParcelType/settings', $data);	
	}

	// Gets the models of settings the correlates to your input fields
	public function getSettingsModelClassName()
	{
		return '\Craft\MyParcelTypeSettingsModel.php';
	}
}

ParcelSchedule API

ParcelSchedule's' allow you to create your own logic for when to send parcels. Before a parcel is sent, it is passed to the ParcelSchedule where it will determine when the parcel should be sent. The ParcelSchedule class is responsible for setting the sendDate property on the Postmaster_TransportModel. ParcelSchedule and NotificationSchedule are pretty much the same thing, except only ParcelSchedule classes will appear in the Parcels section in the control panel.

<?php
namespace Craft;

use Craft\Craft;
use Carbon\Carbon;
use Craft\Plugins\Postmaster\Components\BaseParcelSchedule;

class MyParcelSchedule extends BaseParcelSchedule {
	
	public function getName()
	{
		return Craft::t('My Parcel Schedule');
	}

	public function getId()
	{
		return 'myparcel';
	}

    public function shouldSend($lastSent = false)
    {
        // If $lastSent is false, then this parcel has not been sent yet.
        // If the parcel has been sent, $lastSent will be a Carbon\Carbon
        // object. This method is triggered before the onBeforeSend() method.

        // If your return false, the parcel will not be send.
        return true;
    }

    public function onBeforeSend(Postmaster_TransportModel $model)
    {
        // Do something before the parcel is sent, like set the Postmaster_TransportModel
        // send date for the future. If the sendDate is in the future, the parcel will be
        // send to the queue. The big difference between this and the shouldSend() method
        // is this method is the last chance to prevent the parcel from being sent, or
        // you can send it in the future.

        // You must pass a Carbon\Carbon object to the setSendDate method
        // $model->setSendDate(Carbon::parse('01/01/2015 02:30:00'));

        // Return false if you want to prevent the parcel from sending.
        // If your do return false, the sendDate will be ignored entirely.
        // return false;

        return true;
    }

    public function onAfterSend(Postmaster_TransportResponseModel $model)
    {
        // Do something after the parcel is sent, like alter the Postmaster_TransportResponseModel
        // This model doesn't need to return anything.
    }

	public function getInputHtml(Array $data = array())
	{
		return $this->craft()->templates->render('myplugin/parcel_schedules/my_parcel/settings', $data);	
	}

	public function getSettingsModelClassName()
	{
		return '\Craft\MyPlugin_MyParcelScheduleSettingsModel';
	}
}

NotificationType API

NotificationType's allow you to create different types of notifications that do different things than the default functionality. These notifications can fire at anytime and can perform any arbitrary code you need. The great thing about creating your own NotificationType compared to rolling your own solution is that that you inherent all the services and scheduling provided by Postmaster. For instances, you can can create your own interface, settings, and event binding logic, then pass all that to whatever service and schedule the user chose. It's extremely fast to create custom notifications using NotificationType's.

<?php
namespace Craft;

use Craft\Craft;
use Craft\Plugins\Postmaster\Components\BaseNotificationType;

class MyNotificationNotificationType extends BaseNotificationType {
	
	public function getName()
	{
		return Craft::t('My Notification');
	}

	public function getId()
	{
		return 'default';
	}

	public function parse(Array $data = array())
	{
		// Add your own parsing to this notification type

		// Call the parent functionality if desired.
		parent::parse($data);
	}

	public function onBeforeSend(Postmaster_TransportModel $model)
	{
		// If you return false, the notification will not be sent
		return true;
	}

	public function onAfterSend(Postmaster_TransportResponseModel $model)
	{
		// Do something after the notification has been sent

		return;
	}

	public function getInputHtml(Array $data = array())
	{
		return $this->craft()->templates->render('myplugin/notification_types/my_notification/fields', $data);	
	}

	public function getSettingsInputHtml(Array $data = array())
	{
		return $this->craft()->templates->render('myplugin/notification_types/my_notification/settings', $data);	
	}

	public function getSettingsModelClassName()
	{
		return '\Craft\Postmaster_DefaultNotificationTypeSettingsModel';
	}
}

NotificationSchedule API

NotificationSchedule's' allow you to create your own logic for when to send notifications. Before a notification is sent, it is passed to the NotificationSchedule where it will determine when the notification should be sent. The NotificationSchedule class is responsible for setting the sendDate property on the Postmaster_TransportModel and preventing notifications from being sent unnecessarily. NotificationSchedule and ParcelSchedule are pretty much the same thing, except only NotificationSchedule classes will appear in the Notifications section in the control panel.

<?php
namespace Craft;

use Craft\Craft;
use Carbon\Carbon;
use Craft\Plugins\Postmaster\Components\BaseNotificationSchedule;

class MyNotificationSchedule extends BaseNotificationSchedule {
    
    public function getName()
    {
    	return Craft::t('My Notification Schedule');
    }

    public function getId()
    {
    	return 'mynotification';
    }

    public function shouldSend($lastSent = false)
    {
        // If $lastSent is false, then this notification has not been sent yet.
        // If the notification has been sent, $lastSent will be a Carbon\Carbon
        // object. This method is triggered before the onBeforeSend() method.

        // If your return false, the notification will not be send.
        return true;
    }

    public function onBeforeSend(Postmaster_TransportModel $model)
    {
        // Do something before the notification is sent, like set the Postmaster_TransportModel
        // send date for the future. The big difference between this and the shouldSend() method
        // is this method is the last chance to prevent the notification from being sent, or
        // you can set sendDate to a date in the future.

        // You must pass a Carbon\Carbon object to the setSendDate method
        // $model->setSendDate(Carbon::parse('01/01/2015 02:30:00'));

        // Return false if you want to prevent the notification from sending.
        // If your do return false, the sendDate will be ignored entirely.
        // return false;

        return true;
    }

    public function onAfterSend(Postmaster_TransportResponseModel $model)
    {
        // Do something after the notification is sent, like alter the Postmaster_TransportResponseModel
        // This model doesn't need to return anything.

        return;
    }

    public function getInputHtml(Array $data = array())
    {
        return $this->craft()->templates->render('myplugin/notification_schedules/my_notification/settings', $data); 
    }

    public function getSettingsModelClassName()
    {
        return '\Craft\MyPlugin_MyNotificationScheduleSettingsModel';
    }
}

Service API

Services are the classes that actually facilitate the sending of requests. The Services API allows developers to perform arbitrary logic to send a message with any service.

	<?php
namespace Craft;

use Craft\Craft;
use Craft\Postmaster_TransportModel;
use Craft\Plugins\Postmaster\Components\BaseService;
use \Guzzle\Http\Client;

class MyService extends BaseService {

	// Your service's name
	public function getName()
	{
		return Craft::t('My Service');
	}

	// Your service's camelCased unique id
	public function getId()
	{
		return 'myService';
	}

	// Your service can require certain types of models to be passed to it
	// before it can send. For instance, if you have an email service, you
	// can force the Postmaster_TransportModel to contain an EmailModel
	// before it can send. 
	protected $requiredModels = array(
		'Craft\EmailModel'
	);

	// Send the Postmaster_TransportModel
	public function send(Postmaster_TransportModel $model)
	{
		// Try to perform the send request and catch the errors if it fails			
		try
		{
			// Create a new Guzzle Http client
			$client = new Client();
			
			// Create a new post request with t
			$request = $client->post('some url', array(), array('somePostVar' => 'some data'));

			// Send the request
			$request->send();

			// Send a successful response (default response code is 200)
			return $this->success($model);
		}
		catch(\Exception $e)
		{
			// Send a failed response (default response code is 400)
			return $this->failed($model, 400, array($e->getMessage());
		}
	}

	public function onBeforeSend(Postmaster_TransportModel $model)
	{
		// If you return false, the notification will not be sent
		return true;
	}

	public function onAfterSend(Postmaster_TransportResponseModel $model)
	{
		// Do something after the notification has been sent

		return;
	}

	// Get the settings input html
	public function getInputHtml(Array $data = array())
	{
		return $this->craft()->templates->render('myplugin/my_service/settings', $data);
	}

	// Get the settings model class name
	public function getSettingsModelClassName()
	{
		return '\Craft\MyPlugin_MyServiceSettingsModel';
	}
}

Events

In addition to extending core classes, Postmaster calls a few events for developers to take control over parcels and notifications. You can use these events in the same way native Craft events are handled.

Parcel Events

onBeforeSend

The onBeforeSend event is triggered before a parcel is sent. The event has one parameter, which is transport and is the Postmaster_TransportModel instance used to transport the data from the parcel to the service (where it will be sent).

craft()->postmaster_parcels->on('beforeSend', function(Event $event)
{
    // To prevent the email from sending set performAction to false
    // $event->performAction = false;
});

onAfterSend

The onAfterSend event is triggered after a parcel is sent. The event has one parameter, which is response and is the Postmaster_TransportResponseModel instance that contains information from the service about the parcel that was just sent..

craft()->postmaster_parcels->on('afterSend', function(Event $event)
{

});

onSendComplete

The onSendComplete event is triggered after a parcel has been sent and all the records have been made in the db marking the transaction complete. The event has one parameter, which is response and is the Postmaster_TransportResponseModel instance that contains information from the service about the parcel that was just sent.

craft()->postmaster_parcels->on('sendComplete', function(Event $event)
{

});

onSendFailed

The onSendFailed event is triggered after a parcel has failed to send. The event has one parameter, which is response and is the Postmaster_TransportResponseModel instance that contains information from the service about the parcel that was just sent.

craft()->postmaster_parcels->on('sendFailed', function(Event $event)
{

});

Notification Events

onBeforeSend

The onBeforeSend event is triggered before a notification is sent. The event has one parameter, which is transport and is the Postmaster_TransportModel instance used to transport the data from the notification to the service (where it will be sent).

craft()->postmaster_notifications->on('beforeSend', function(Event $event)
{
    // To prevent the email from sending set performAction to false
    // $event->performAction = false;
});

onAfterSend

The onAfterSend event is triggered after a notification is sent. The event has one parameter, which is response and is the Postmaster_TransportResponseModel instance that contains information from the service about the notification that was just sent.

craft()->postmaster_notifications->on('afterSend', function(Event $event)
{

});

onSendComplete

The onSendComplete event is triggered after a notification has been sent and all the records have been made in the db marking the transaction complete. The event has one parameter, which is response and is the Postmaster_TransportResponseModel instance that contains information from the service about the notification that was just sent.

craft()->postmaster_notifications->on('sendComplete', function(Event $event)
{

});

onSendFailed

The onSendFailed event is triggered after a notification has failed to send. The event has one parameter, which is response and is the Postmaster_TransportResponseModel instance that contains information from the service about the notification that was just sent.

craft()->postmaster_notifications->on('sendFailed', function(Event $event)
{

});