PHP code example of bestit / commercetools-odm

1. Go to this page and download the library: Download bestit/commercetools-odm library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bestit / commercetools-odm example snippets




// Load the product repository.
/** @var \BestIt\CommercetoolsODM\DocumentManagerInterface $documentManager */
/** @var \BestIt\CommercetoolsODM\Repository\ProductRepository $repository */
$repository = $documentManager->getRepository(\Commercetools\Core\Model\Product\Product::class);

// Fetch it from the database or create a new instance.
/** @var \Commercetools\Core\Model\Product\Product $product */
$product = $repository->findByKey($key) ??
    $documentManager->getClassMetadata(\Commercetools\Core\Model\Product\Product::class)->getNewInstance();

// Do your work.
if (!$product->getId()) {
    $product
        ->setProductType(\Commercetools\Core\Model\ProductType\ProductTypeReference::ofId('type'))
        // ....
}

// You get automatic but simple 409 conflict resolution if you use  this callback. If not, 409s lead to an exception. 
$documentManager->modify($product, function(\Commercetools\Core\Model\Product\Product $product) {
    $product->setKey('new-key');
});

// Persist the changes
$documentManager->persist($product);

// Detach it from the document manager (UnitOfWork) after flush.
$documentManager->detachDeferred($product);

// Flush the changes in the document manager to the repository.
$documentManager->flush();



// ./src/Resources/config/metadata.php

use BestIt\CommercetoolsODM\Mapping\Annotations\RequestMap;

return [
    // Your model
    \Commercetools\Core\Model\Cart\Cart::class => [
        // The draft class for creating a new model
        'draft' => \Commercetools\Core\Model\Cart\CartDraft::class,
        // Which repo to use
        'repository' => \BestIt\CommercetoolsODM\Repository\CartRepository::class,
        // And the map for every needed request type.
        'requestClassMap' => (new RequestMap())
            ->setCreate(\Commercetools\Core\Request\Carts\CartCreateRequest::class)
            ->setDeleteById(\Commercetools\Core\Request\Carts\CartDeleteRequest::class)
            ->setFindById(\Commercetools\Core\Request\Carts\CartByIdGetRequest::class)
            ->setFindByCustomerId(\Commercetools\Core\Request\Carts\CartByCustomerIdGetRequest::class)
            ->setQuery(\Commercetools\Core\Request\Carts\CartQueryRequest::class)
            ->setUpdateById(\Commercetools\Core\Request\Carts\CartUpdateRequest::class)
    ],

    // ... map more models
];