Service contracts in magento 2

You can implement service contracts by applying this codes as it is hopefully there is no error in writing . I wold like to explain my code but unfortunately i am unable to give proper detail because of time for more info contact at asadu0765@gmail.com.  i would like to thank my Ustaad Adnan who taught me all this.

 

Custom/Module/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Custom_Module',
__DIR__
);

 

../etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Custom_Module" setup_version="1.0.0" />
</config>

../Setup/InstallSchema.php

<?php
namespace Custom\Module\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;
class InstallSchema implements InstallSchemaInterface {
public function install( SchemaSetupInterface $setup, ModuleContextInterface $context ) {
$installer = $setup;
$installer->startSetup();
$table = $installer->getConnection()->newTable(
$installer->getTable( 'ad_shipping_quote' )
)->addColumn(
'entity_id',
Table::TYPE_SMALLINT,
null,
[ 'identity' => true, 'nullable' => false, 'primary' => true ],
'Post ID'
)->addColumn(
'product_id',
Table::TYPE_SMALLINT,
255,
[ ],
'Post ID'
)
->addColumn(
'customer_name',
Table::TYPE_TEXT,
255,
[ 'nullable' => false ],
'Post Title'
)

->addColumn(
'customer_email',
Table::TYPE_TEXT,
'2M',
[ ],
'Post Content'
) ->addColumn(
'customer_comments',
Table::TYPE_TEXT,
255,
[ 'nullable' => false ],
'Post Title'
)->addColumn(
'date_added',
Table::TYPE_TEXT,
255,
[ 'nullable' => false ],
'Post Title'
)->addColumn(
'date_updated',
Table::TYPE_TEXT,
255,
[ 'nullable' => false ],
'Post Title'
)
->setComment(
'Ad Shipping Quote Table'
);
$installer->getConnection()->createTable( $table );
$installer->endSetup();
}
}

 

../etc/di.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Custom\Module\Api\ModelRepositoryInterface"
type="Custom\Module\Model\ModelRepository" />
<preference for="Custom\Module\Api\Data\ModelInterface"
type="Custom\Module\Model\Model" />
<preference for="Custom\Module\Api\Data\ModelSearchResultsInterface"
type="Custom\Module\Model\ModelSearchResults" />
</config>

 

../etc/webapi.xml

<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">

<route method="GET" url="/V1/model/:id">
<service class="Custom\Module\Api\ModelRepositoryInterface" method="getById"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>

<route method="GET" url="/V1/model">
<service class="Custom\Module\Api\ModelRepositoryInterface" method="getList"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>

../Api/ModelRepositoryInterface.php

<?php
namespace Custom\Module\Api;

use \Custom\Module\Api\Data\ModelInterface;
use \Magento\Framework\Api\SearchCriteriaInterface;

interface ModelRepositoryInterface
{
/**
* @api
* @param \Custom\Module\Api\Data\ModelInterface $model
* @return \Custom\Module\Api\Data\ModelInterface
*/
public function save(ModelInterface $model);

/**
* @api
* @param \Custom\Module\Api\Data\ModelInterface $model
* @return \Custom\Module\Api\Data\ModelInterface
*/
public function delete(ModelInterface $model);

/**
* @api
* @param \Custom\Module\Api\Data\ModelInterface $id
* @return void
*/
public function deleteById($id);

/**
* @api
* @param int $id
* @return \Custom\Module\Api\Data\ModelInterface
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getById($id);

/**
* @api
* @param \Magento\Framework\Api\SearchCriteriaInterface $criteria
* @return \Custom\Module\Api\Data\ModelSearchResultsInterface
*/
public function getList(SearchCriteriaInterface $criteria);
}

../Api/Data/ModelInterface.php

<?php
namespace Custom\Module\Api\Data;

interface ModelInterface
{
/**
* Return the Entity ID
*
* @return int
*/
public function getEntityId();

/**
* Set Entity ID
*
* @param int $id
* @return $this
*/
public function setEntityId($id);

/**
* Return the Product ID associated with Quote
*
* @return int
*/
public function getProductId();

/**
* Set the Product ID associated with Quote
*
* @param int $productId
* @return $this
*/
public function setProductId($productId);

/**
* Return the Customer Name
*
* @return string
*/
public function getCustomerName();

/**
* Set the Customer Name
*
* @param string $customerName
* @return $this
*/
public function setCustomerName($customerName);

/**
* Return the Customer Email
*
* @return string
*/
public function getCustomerEmail();

/**
* Set the Customer Email
*
* @param string $customerEmail
* @return $this
*/
public function setCustomerEmail($customerEmail);

/**
* Return the Customer Comments
*
* @return string
*/
public function getCustomerComments();

/**
* Set the Customer Comments
*
* @param string $customerComments
* @return $this
*/
public function setCustomerComments($customerComments);

/**
* Return the Date and Time of record added
*
* @return string
*/
public function getDateAdded();

/**
* Set the Date and Time of record added
*
* @param string $date
* @return $this
*/
public function setDateAdded($date);

/**
* Return the Date and Time of record updated
*
* @return string
*/
public function getDateUpdated();

/**
* Set the Date and Time of record updated
*
* @param string $date
* @return $this
*/
public function setDateUpdated($date);
}

..Api/Data/ModelSearchResultsInterface.php

<?php

namespace Custom\Module\Api\Data;

use Magento\Framework\Api\SearchResultsInterface;

interface ModelSearchResultsInterface extends SearchResultsInterface
{
/**
* @return \Custom\Module\Api\Data\ModelInterface[]
*/
public function getItems();

/**
* @param \Custom\Module\Api\Data\ModelInterface[] $items
* @return $this
*/
public function setItems(array $items);
}

../Model/Model.php

<?php

namespace Custom\Module\Model;

use Custom\Module\Api\Data\ModelInterface;

class Model extends \Magento\Framework\Model\AbstractModel implements
\Custom\Module\Api\Data\ModelInterface
{
protected function _construct()
{
$this->_init('Custom\Module\Model\ResourceModel\Model');
}

/**
* @inheritdoc
*/
public function getEntityId()
{
return $this->_getData('entity_id');
}

/**
* @inheritdoc
*/
public function setEntityId($id)
{
$this->setData('entity_id', $id);
}

/**
* @inheritdoc
*/
public function getProductId()
{
return $this->_getData('product_id');
}

/**
* @inheritdoc
*/
public function setProductId($productId)
{
$this->setData('product_id', $productId);
}

/**
* @inheritdoc
*/
public function getCustomerName()
{
return $this->_getData('customer_name');
}

/**
* @inheritdoc
*/
public function setCustomerName($customerName)
{
$this->setData('customer_name', $customerName);
}

/**
* @inheritdoc
*/
public function getCustomerEmail()
{
return $this->_getData('customer_email');
}

/**
* @inheritdoc
*/
public function setCustomerEmail($customerEmail)
{
$this->setData('customer_email', $customerEmail);
}

/**
* @inheritdoc
*/
public function getCustomerComments()
{
return $this->_getData('customer_comments');
}

/**
* @inheritdoc
*/
public function setCustomerComments($customerComments)
{
$this->setData('customer_comments', $customerComments);
}

/**
* @inheritdoc
*/
public function getDateAdded()
{
return $this->_getData('date_added');
}

/**
* @inheritdoc
*/
public function setDateAdded($date)
{
$this->setData('date_added', $date);
}

/**
* @inheritdoc
*/
public function getDateUpdated()
{
return $this->_getData('date_updated');
}

/**
* @inheritdoc
*/
public function setDateUpdated($date)
{
$this->setData('date_updated', $date);
}
}

../Model/ResourceModel/Model.php

<?php

namespace Custom\Module\Model\ResourceModel;

class Model extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
protected $_idFieldName = 'entity_id';

protected function _construct()
{
$this->_init('ad_shipping_quote','entity_id');
}
}

../Model/ResourceModel/Model/Collection.php

<?php

namespace Custom\Module\Model\ResourceModel\Model;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected $_idFieldName = 'entity_id';
protected $_eventPrefix = 'ad_shipping_quote_collection';
protected $_eventObject = 'quote_collection';

protected function _construct()
{
$this->_init('Custom\Module\Model\Model', 'Custom\Module\Model\ResourceModel\Model');
}
}

../Model/ModelRepository.php

<?php
namespace Custom\Module\Model;

use \Custom\Module\Api\Data\ModelInterface;
use \Custom\Module\Model\ResourceModel\Model as ObjectResourceModel;
use \Magento\Framework\Api\SearchCriteriaInterface;
use \Magento\Framework\Exception\CouldNotSaveException;
use \Magento\Framework\Exception\NoSuchEntityException;
use \Magento\Framework\Exception\CouldNotDeleteException;

class ModelRepository implements \Custom\Module\Api\ModelRepositoryInterface
{
protected $objectFactory;

protected $objectResourceModel;

protected $collectionFactory;

protected $searchResultsFactory;

public function __construct(
\Custom\Module\Model\ModelFactory $objectFactory,
ObjectResourceModel $objectResourceModel,
\Custom\Module\Model\ResourceModel\Model\CollectionFactory $collectionFactory,
\Magento\Framework\Api\SearchResultsInterfaceFactory $searchResultsFactory
) {
$this->objectFactory = $objectFactory;
$this->objectResourceModel = $objectResourceModel;
$this->collectionFactory = $collectionFactory;
$this->searchResultsFactory = $searchResultsFactory;
}

public function save(ModelInterface $object)
{
$name = $object->getCustomerName();
$hasSpouse = $object->getSpouse();
if ($hasSpouse == true) {
$name = "Mrs. " . $name;
} else {
$name = "Miss. " . $name;
}
$object->setCustomerName($name);
try {
$this->objectResourceModel->save($object);
} catch (\Exception $e) {
throw new CouldNotSaveException(__($e->getMessage()));
}
return $object;
}

/**
* @inheritdoc
*/
public function getById($id)
{
$object = $this->objectFactory->create();
$this->objectResourceModel->load($object, $id);
if (!$object->getId()) {
throw new NoSuchEntityException(__('Object with id "%1" does not exist.', $id));
}
return $object;
}

public function delete(ModelInterface $object)
{
try {
$this->objectResourceModel->delete($object);
} catch (\Exception $exception) {
throw new CouldNotDeleteException(__($exception->getMessage()));
}
return true;
}

public function deleteById($id)
{
return $this->delete($this->getById($id));
}

/**
* @inheritdoc
*/
public function getList(SearchCriteriaInterface $criteria)
{
$searchResults = $this->searchResultsFactory->create();
$searchResults->setSearchCriteria($criteria);
$collection = $this->collectionFactory->create();
foreach ($criteria->getFilterGroups() as $filterGroup) {
$fields = [];
$conditions = [];
foreach ($filterGroup->getFilters() as $filter) {
$condition = $filter->getConditionType() ? $filter->getConditionType() : 'eq';
$fields[] = $filter->getField();
$conditions[] = [$condition => $filter->getValue()];
}
if ($fields) {
$collection->addFieldToFilter($fields, $conditions);
}
}
$searchResults->setTotalCount($collection->getSize());
$sortOrders = $criteria->getSortOrders();
if ($sortOrders) {
/** @var SortOrder $sortOrder */
foreach ($sortOrders as $sortOrder) {
$collection->addOrder(
$sortOrder->getField(),
($sortOrder->getDirection() == SortOrder::SORT_ASC) ? 'ASC' : 'DESC'
);
}
}
$collection->setCurPage($criteria->getCurrentPage());
$collection->setPageSize($criteria->getPageSize());
$objects = [];
foreach ($collection as $objectModel) {
$objects[] = $objectModel;
}
$searchResults->setItems($objects);
return $searchResults;
}
}

../Model/ModelSearchResults.php

<?php

namespace Custom\Module\Model;

use \Magento\Framework\Api\SearchResults;
use \Custom\Module\Api\Data\ModelSearchResultsInterface;

class ModelSearchResults extends SearchResults implements ModelSearchResultsInterface
{

}

../Controller/Index/Save.php

<?php

namespace Custom\Module\Controller\Index;

use \Magento\Framework\Controller\Result\RawFactory;

class Save extends \Magento\Framework\App\Action\Action
{

/**
* Index resultPageFactory
* @var PageFactory
*/
private $resultPageFactory;
/**
* @var
*/
private $modelFactory;
/**
* @var
*/
private $modelRepository;

/**
* Index constructor.
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
* @param \Custom\Module\Model\ModelFactory $modelFactory
* @param \Custom\Module\Model\ModelRepository $modelRepository
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Custom\Module\Model\ModelFactory $modelFactory,
\Custom\Module\Model\ModelRepository $modelRepository
) {
$this->resultPageFactory = $resultPageFactory;
$this->modelFactory = $modelFactory;
$this->modelRepository = $modelRepository;
return parent::__construct($context);

}

/**
* @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$data = [

"product_id" => 201,
"customer_name" => "Katrina",
"customer_email" => "karina@kapoor.com",
"spouse" => 1
];

$obj = $this->modelFactory->create();
$this->modelRepository->save($obj->addData($data)); // Service Contract

//$obj->addData($data)->save(); // Model / Resource Model

$this->resultFactory->create("raw");
}
}

../Controller/Index/Getlist.php

<?php

namespace Custom\Module\Controller\Index;

use \Magento\Framework\Controller\Result\RawFactory;

class Getlist extends \Magento\Framework\App\Action\Action
{

/**
* Index resultPageFactory
* @var PageFactory
*/
private $resultPageFactory;
/**
* @var
*/
private $modelFactory;
/**
* @var
*/
private $modelRepository;
/**
* @var
*/
private $searchCriteriaBuilder;

/**
* Index constructor.
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
* @param \Custom\Module\Model\ModelRepository $modelRepository
* @param \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Custom\Module\Model\ModelRepository $modelRepository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
) {
$this->resultPageFactory = $resultPageFactory;
$this->modelRepository = $modelRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
return parent::__construct($context);
}

/**
* @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$_filter = $this->searchCriteriaBuilder
->addFilter("customer_name", "%na%", "like")->create();
$list = $this->modelRepository->getList($_filter);
$results = $list->getItems();
foreach ($results as $result) {
echo $result->getCustomerName() . "<br>";
}

$this->resultFactory->create("raw");
}
}

../Controller/Index/Getbyid.php

<?php

namespace Custom\Module\Controller\Index;

use \Magento\Framework\Controller\Result\RawFactory;

class Getbyid extends \Magento\Framework\App\Action\Action
{

/**
* Index resultPageFactory
* @var PageFactory
*/
private $resultPageFactory;
/**
* @var
*/
private $modelRepository;

/**
* Index constructor.
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
* @param \Custom\Module\Model\ModelRepository $modelRepository
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Custom\Module\Model\ModelRepository $modelRepository

) {
$this->resultPageFactory = $resultPageFactory;
$this->modelRepository = $modelRepository;
return parent::__construct($context);
}

public function execute()
{

$search = $this->modelRepository->getById(1);
print_r($search->getData());

$this->resultFactory->create("raw");
}
}
../Controller/Index/Deletebyid.php

<?php

namespace Custom\Module\Controller\Index;

use \Magento\Framework\Controller\Result\RawFactory;

class Deletbyid extends \Magento\Framework\App\Action\Action
{

/**
* Index resultPageFactory
* @var PageFactory
*/
private $resultPageFactory;
/**
* @var
*/
private $modelRepository;

/**
* Index constructor.
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
* @param \Custom\Module\Model\ModelRepository $modelRepository
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Custom\Module\Model\ModelRepository $modelRepository

) {
$this->resultPageFactory = $resultPageFactory;
$this->modelRepository = $modelRepository;
return parent::__construct($context);
}

public function execute()
{

$this->modelRepository->deleteById(1);

$this->resultFactory->create("raw");
}
}

../Controller/Index/Del.php

<?php

namespace Custom\Module\Controller\Index;

use \Magento\Framework\Controller\Result\RawFactory;

class Del extends \Magento\Framework\App\Action\Action
{

/**
* Index resultPageFactory
* @var PageFactory
*/
private $resultPageFactory;
/**
* @var
*/
private $modelRepository;

/**
* Index constructor.
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
* @param \Custom\Module\Model\ModelFactory $modelFactory
* @param \Custom\Module\Model\ModelRepository $modelRepository
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Custom\Module\Model\ModelFactory $modelFactory,
\Custom\Module\Model\ModelRepository $modelRepository

) {
$this->resultPageFactory = $resultPageFactory;
$this->modelFactory = $modelFactory;
$this->modelRepository = $modelRepository;
return parent::__construct($context);
}

public function execute()
{
$obj = $this->modelFactory->create()->load(2);
$this->modelRepository->delete($obj);

$this->resultFactory->create("raw");
}
}

One Comment on “Service contracts in magento 2”

Leave a Reply

Your email address will not be published. Required fields are marked *