Как вызвать getService $this->modx в наследуемом классе?

MODX Revolution 2.8.3-pl

Как вызвать getService $this->modx в наследуемом классе, чтобы воспользоваться функциями из другого компонента?

Например в обработчике корзины:
<?php
class msCartCustomHandler extends msCartHandler {
}
Кровельный
24 мая 2024, 18:02
modx.pro
1
188
0

Комментарии: 3

Андрей Степаненко
26 мая 2024, 09:26
+1
Чтобы вызвать метод `getService` в наследуемом классе в MODX Revolution 2.8.3-pl, нужно использовать объект `$this->modx`. В вашем случае, чтобы воспользоваться функциями из другого компонента в обработчике корзины, можно сделать это следующим образом:

<?php
class msCartCustomHandler extends msCartHandler {
    public function __construct(modX & $modx, array $config = array()) {
        parent::__construct($modx, $config);
        // Ваш код инициализации здесь
    }

    public function someMethod() {
        // Пример вызова метода getService
        $myService = $this->modx->getService('myComponent', 'MyComponent', $this->modx->getOption('myComponent.core_path', null, $this->modx->getOption('core_path').'components/myComponent/').'model/myComponent/');
        
        if ($myService instanceof MyComponent) {
            // Использование методов компонента
            $myService->someComponentMethod();
        }
    }
}
?>
1. **Инициализация класса**: В конструкторе класса `msCartCustomHandler` вызывается конструктор родительского класса `msCartHandler`, чтобы корректно инициализировать объект.
2. **Вызов `getService`**: В методе `someMethod` происходит вызов `getService`, который загружает и инициализирует необходимый компонент (в данном примере `myComponent`).
3. **Проверка и использование**: Проверяется, что возвращаемое значение действительно является экземпляром необходимого класса компонента, после чего можно использовать методы этого компонента.

Этот подход позволяет вам гибко использовать функциональность различных компонентов MODX в вашем наследуемом классе.
    Кровельный
    27 мая 2024, 11:11
    0
    Не получается присоединить конструктор, а при вызове someMethod() ошибка 500.
    <?php
    class msCartCustomHandler extends msCartHandler {
        public function __construct(modX & $modx, array $config = array()) {
            parent::__construct($modx, $config);
            // Ваш код инициализации здесь
        }
    
        public function someMethod() {
            // Пример вызова метода getService
            $cityFields = $this->modx->getService('cityfields','cityFields', $this->modx->getOption('cityfields.core_path', null, $this->modx->getOption('core_path').'components/cityfields/').'model/cityfields/');
            
            if ($cityFields instanceof cityFields) {
                // Использование методов компонента
                return $cityFields->currentCityId();
            }
        }
    	
        /**
         * @param array $data
         *
         * @return array
         */
        public function status($data = array())
        {
            $status = [
                'total_count' => 0,
                'total_cost' => 0,
                'total_weight' => 0,
                'total_discount' => 0,
                'total_positions' => count($this->cart),
            ];
            foreach ($this->cart as $item) {
                if (empty($item['ctx']) || $item['ctx'] == $this->ctx) {
                    $status['total_count'] += $item['count'];
                    $status['total_cost'] += $item['price'] * $item['count'];
                    $status['total_weight'] += $item['weight'] * $item['count'];
                    $status['total_discount'] += $item['discount_price'] * $item['count'];
                }
            }
    
            $status = array_merge($data, $status);
    
            $response = $this->ms2->invokeEvent('msOnGetStatusCart', [
                'status' => $status,
                'cart' => $this,
            ]);
            if ($response['success']) {
                $status = $response['data']['status'];
            }
            $this->modx->log(1, print_r($this->someMethod(), 1));
    
            return $status;
        }
    }
    ?>
      Кровельный
      27 мая 2024, 14:06
      0
      А вот этот код, передаёт нормально через конфиг:
      <?php
      class msCartCustomHandler extends msCartHandler {
          /**
          * msCartCustomHandler constructor.
          *
          * @param miniShop2 $ms2
          * @param array $config
          */
          public function __construct(miniShop2 $ms2, array $config = array())
          {
              $this->ms2 = $ms2;
              $this->modx = $ms2->modx;
      
              $cityFields = $this->modx->getService('cityfields','cityFields', $this->modx->getOption('cityfields.core_path', null, $this->modx->getOption('core_path').'components/cityfields/').'model/cityfields/');
              if ($cityFields instanceof cityFields) {
                  if (!empty($cityFields->currentCityId)) {
                      $currentCityId = $cityFields->currentCityId;
                  }
                  
              }
              $this->config = array_merge(array(
                  'currentCityId' => $currentCityId,
                  'cart' => & $_SESSION['minishop2']['cart'],
                  'max_count' => $this->modx->getOption('ms2_cart_max_count', null, 1000, true),
                  'allow_deleted' => false,
                  'allow_unpublished' => false,
              ), $config);
      
              $this->cart = &$this->config['cart'];
              $this->modx->lexicon->load('minishop2:cart');
      
              if (empty($this->cart) || !is_array($this->cart)) {
                  $this->cart = array();
              }
          }
          
         /**
           * @param array $data
           *
           * @return array
           */
          public function status($data = array())
          {
              $status = [
                  'total_count' => 0,
                  'total_cost' => 0,
                  'total_weight' => 0,
                  'total_discount' => 0,
                  'total_positions' => count($this->cart),
              ];
              foreach ($this->cart as $item) {
                  if (empty($item['ctx']) || $item['ctx'] == $this->ctx) {
                      $status['total_count'] += $item['count'];
                      $status['total_cost'] += $item['price'] * $item['count'];
                      $status['total_weight'] += $item['weight'] * $item['count'];
                      $status['total_discount'] += $item['discount_price'] * $item['count'];
                  }
              }
      
              $status = array_merge($data, $status);
      
              $response = $this->ms2->invokeEvent('msOnGetStatusCart', [
                  'status' => $status,
                  'cart' => $this,
              ]);
              if ($response['success']) {
                  $status = $response['data']['status'];
              }
              $this->modx->log(1, print_r($this->config['currentCityId'], 1));
      
              return $status;
          }
      }
      ?>
    Авторизуйтесь или зарегистрируйтесь, чтобы оставлять комментарии.
    3