WordPress: creare una classe di base per gestire le richieste AJAX

WordPress: creare una classe di base per gestire le richieste AJAX

In WordPress possiamo creare una semplice classe di base per gestire le richieste AJAX.

Possiamo creare la seguente classe:


class WP_Ajax_Wrapper {

	protected $_actions = array();
	protected $_types;

	public function __construct( $contentTypes ) {
		$this->_types = $contentTypes;
	}

	public function addAction( $name, $visibility, $method ) {
		$this->_actions[] = array(
			'name' => $name,
			'visibility' => $visibility,
			'method' => $method
		);
	}

	public function registerActions( $reference ) {
		$actions = $this->_actions;
		if( count( $actions ) == 0 ) {
			return;
		}
		foreach( $actions as $action ) {
			$visibility = $action['visibility'];
			if( $visibility == 'all' ) {
				add_action( 'wp_ajax_' . $action['name'], array( $reference, $action['method'] ) );
				add_action( 'wp_ajax_nopriv_' . $action['name'], array( $reference, $action['method'] ) );
			} else if( $visibility == 'public' ) {
				add_action( 'wp_ajax_nopriv_' . $action['name'], array( $reference, $action['method'] ) );	
			} else {
				add_action( 'wp_ajax_' . $action['name'], array( $reference, $action['method'] ) );	
			}
		}
	}

	public function setContentType( $type = 'application/json' ) {
		$allowed = $this->_types;
		if( !in_array( $type, $allowed ) ) {
			return;
		}
		header( 'Content-Type: ' . $type );
	}


}

Esempio d'uso:


require_once( 'WP_Ajax_Wrapper.php' );

class My_Ajax {
	protected $_ajax;

	public function __construct() {
		$this->_ajax = new WP_Ajax_Wrapper( array( 'application/json', 'text/xml' ) );
		$this->actions();
		$this->_ajax->registerActions( $this );
	}

	public function actions() {
		$this->_ajax->addAction( 'test', 'all', 'foo' );
		$this->_ajax->addAction( 'bar', 'all', 'bar' );
	}

	public function foo() {
		$this->_ajax->setContentType( 'text/xml' );
		echo '<foo>ok</foo>';
		exit();
	}

	public function bar() {
		$this->_ajax->setContentType( 'application/json' );	
		echo json_encode( array( 'ok' => 'bar' ) );
		exit();
	}
}

$myAjax = new My_Ajax();

Torna su