WordPress: creare una classe wrapper per gestire AJAX
Per gestire meglio AJAX in WordPress possiamo creare una classe wrapper per semplificare alcuni task.
Per gestire meglio AJAX in WordPress possiamo creare una classe wrapper per semplificare alcuni task.
La nostra classe wrapper sarà la seguente:
class WP_Ajax_Wrapper {
protected $_actions = array(); // Array di nomi di action
protected $_types; // Tipi MIME
public function __construct( $contentTypes ) {
$this->_types = $contentTypes;
}
public function addAction( $name, $visibility, $method ) {
$this->_actions[] = array(
'name' => $name, // Nome action
'visibility' => $visibility, // all, public, private
'method' => $method // Metodo da invocare
);
}
public function registerActions( $reference ) {
// $reference è il riferimento alla classe a cui appartiene
// il metodo della action
$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();
}
}
$myA = new My_Ajax();
Commenti