Giter Club home page Giter Club logo

modxloader's Introduction

ModxLoader

Плагин с классом Loader

Плагин позволяет обращаться к сниппетам как через ajax так и напрямую

Для установки нужно создать плагин Loader с ниже указанным кодом на событие OnWebPageInit

require MODX_BASE_PATH.'assets/plugins/loader/plugin.loader.php';

пример вызова своего сниппета в php

$modx->load->controller('account/controller/login', $config);

'account/controller/login' - путь до нужного сниппета

$config - массив с передаваемыми параметрами


AJAX

$.ajax({
    url: 'ajax?route=account/controller/login/ajax',
    dataType: 'json',
    type: 'post',
    data: params,
    success: function(json) {

	// ваш код

    },
    error: function(xhr, ajaxOptions, thrownError) {
	alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
    }
});

PHP

Сниппеты должны придерживаться правил и находится в папке 'assets/snippets/'

AccountControllerLogin - 'account/controller/login'

<?php
class AccountControllerLogin {

	public function index() {
	
		// ваш код
		
	}
	
}
?>

Или как расширение класса Loader либо любого другого

<?php
class AccountControllerLogin extends Loader {

	public function index() {
	
		// ваш код
		
	}
	
}
?>

Рабочий код можно посмотреть в сниппете ModxAccount

PHP https://github.com/64j/ModxAccount/blob/master/account/controller/login.php

JS ajax - https://github.com/64j/ModxAccount/blob/master/account/view/login.tpl#L57




Также можно установить плагин без инклюда, описанного выше.

Установка:

Событие плагина OnWebPageInit

<?php
// OnWebPageInit

if($modx->Event->name == 'OnWebPageInit') {

	class Loader {
		private $data = array();

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

		public function __get($key) {
			return (isset($this->data[$key]) ? $this->data[$key] : null);
		}

		public function __set($key, $value) {
			$this->data[$key] = $value;
		}

		public function controller($route, $data = array()) {
			// спасибо Agel_Nash https://github.com/AgelxNash
			$parts = explode('/', preg_replace(array(
				'/\.*[\/|\\\]/i',
				'/[\/|\\\]+/i'
			), array(
				'/',
				'/'
			), (string) rtrim($route, '/')));
			while($parts) {
				$file = MODX_BASE_PATH . 'assets/snippets/' . implode('/', $parts) . '.php';
				$class = preg_replace('/[^a-zA-Z0-9]/', '', implode('/', $parts));
				if(is_file($file)) {
					include_once($file);
					break;
				} else {
					$method = array_pop($parts);
				}
			}

			if(!isset($method)) {
				$method = 'index';
			}

			if(substr($method, 0, 2) == '__') {
				return false;
			}

			if($method == 'index' && isset($_GET['route'])) {
				$this->modx->sendRedirect($this->modx->config['site_url']);
			}

			$output = '';

			if(class_exists($class)) {
				$controller = new $class($this->modx);

				if(is_callable(array(
					$controller,
					$method
				))) {
					$output = call_user_func(array(
						$controller,
						$method
					), $data);

				} else {
					$this->modx->sendRedirect($this->modx->config['site_url']);
				}

			} else {
				$this->modx->sendRedirect($this->modx->config['site_url']);
			}

			return $output;
		}
	}

	$modx->load = new Loader($modx);
}


Для работы через ajax можно использовать Ajax метод 4 от Agel_Nash

ajax.php (создать файл в корне сайта)

<?php

define('MODX_API_MODE', true);

include_once(dirname(__FILE__) . "/index.php");

$modx->db->connect();

if (empty ($modx->config)) {
    $modx->getSettings();
}

$modx->invokeEvent("OnWebPageInit");

if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') || ($_SERVER['REQUEST_METHOD'] != 'POST')){
    $modx->sendRedirect($modx->config['site_url']);
}

header('content-type: application/json');

echo $modx->load->controller($_REQUEST['route'], $_REQUEST);

modxloader's People

Contributors

64j avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

ditso

modxloader's Issues

Не вызывается метод index при использовании AJAX

При использовании AJAX не вызывается метод index моего класса.
Причина в проверке на 54 строке
if($method == 'index' && isset($_GET['route']))
т.к. если делать AJAX-запрос на страницу ajax.php и передавать роут без указания метода через query-string т.е. так:
ajax.php?route=test/controller/core
то получается что у запроса есть GET часть route и метод будет index, значит проверка на 54 строке пройдет и плагин сделает редирект...
Вышел из положения добавив в условие проверку метода запроса:
if($method == 'index' && isset($_GET['route']) && $_SERVER['REQUEST_METHOD'] == "GET")

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.