Skip to content

How not to use Object Manager?

i don’t want to use object manager how do i change my code?
in the past i use method cart $cart but he deprecated

     <?php

     namespace CustomShippingMethodModelCarrier;

 use MagentoQuoteModelQuoteAddressRateRequest;
 use MagentoShippingModelCarrierAbstractCarrier;
 use MagentoShippingModelCarrierCarrierInterface;
 use MagentoFrameworkAppConfigScopeConfigInterface;
 use MagentoQuoteModelQuoteAddressRateResultErrorFactory;
 use PsrLogLoggerInterface;
 use MagentoShippingModelRateResultFactory;
 use MagentoQuoteModelQuoteAddressRateResultMethodFactory;
 use MagentoFrameworkObjectManagerInterface;


 class PlanetExpress extends AbstractCarrier implements CarrierInterface
{

protected $_code = 'planetexpress';

protected $rateResultFactory;

protected $rateMethodFactory;

protected $_objectManager;

public function __construct(
    ObjectManagerInterface $objectManager,
    ScopeConfigInterface $scopeConfig,
    ErrorFactory $rateErrorFactory,
    LoggerInterface $logger,
    ResultFactory $rateResultFactory,
    MethodFactory $rateMethodFactory,
    array $data = []
)
{
    $this->_objectManager = $objectManager;
    $this->rateResultFactory = $rateResultFactory;
    $this->rateMethodFactory = $rateMethodFactory;
    parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);
}

public function getAllowedMethods()
{
    return ['planetexpress' => $this->getConfigData('name')];
}

public function collectRates(RateRequest $request)
{
    if (!$this->getConfigFlag('active')) {
        return false;
    }

    /** @var MagentoShippingModelRateResult $result */
    $result = $this->rateResultFactory->create();

    /** @var MagentoQuoteModelQuoteAddressRateResultMethod $method */
    $method = $this->rateMethodFactory->create();
    $method->setCarrier($this->_code);
    $method->setCarrierTitle($this->getConfigData('title'));

    $method->setMethod($this->_code);
    $method->setMethodTitle($this->getConfigData('name'));


    $cart = $this->_objectManager->get('MagentoCheckoutModelCart');

    $uniqueItems = $cart->getQuote()->getItemsCount();
    $totalItems = $cart->getQuote()->getItemsQty();
    $subTotal = $cart->getQuote()->getGrandTotal();

    $amount = $this->getConfigData('price');

    $countryRate = 1;
    if ($request->getDestCountryId() == 'US'){
        $countryRate = 3;
    }elseif ($request->getDestCountryId() == 'UA'){
        $countryRate = 2;
    }elseif ($request->getDestCountryId() == 'CA'){
        $countryRate = 7;
    }

        $shippingPrice = ($subTotal * $uniqueItems * $amount) / $totalItems * $countryRate;

    $method->setPrice($shippingPrice);
    $method->setCost($amount);

    $result->append($method);

    return $result;
}

}