Class ProductsApiV2Controller
Provides a gateway to the ProductWriteService and ProductReadService classes, which handle the shop product resources.
| category |
System |
|---|---|
| package |
ApiV2Controllers |
__construct(\Slim\Slim $api, array $uri)
Call this constructor from every child controller class in order to set the Slim instance and the request routes arguments to the class.
| deprecated |
The "__initialize" method will is deprecated and will be removed in a future version. Please use the new "init" for bootstrapping your child API controllers. |
|---|---|
| Throws |
|
\Slim\SlimSlim framework instance, used for request/response manipulation.
arrayThis array contains all the segments of the current request, starting from the resource.
__initialize()
_linkResponse(array &$response)
The APIv2 operates with simple resources that might be linked with other resources. This architecture promotes flexibility so that API consumers can have a simpler structure. This method will search for existing external resources and will add a link to the end of each resource.
IMPORTANT: If for some reason you need to include custom links to your resources do not use this method. Include them inside your controller method manually.
NOTICE #1: This method will only search at the first level of the resource. That means that nested ID values will not be taken into concern.
NOTICE #2: You can provide both associative (single response item) or sequential (multiple response items) arrays and this method will adjust the links accordingly.
arrayPassed by reference, new links will be appended into the end of each resource.
_locateResource(string $p_name, integer $p_id)
Use this method whenever you want the "Location" header to point to an existing resource so that clients can use it to fetch that resource without having to generate the URL themselves.
| Throws |
|
|---|
string
integer
_mapResponse(array $criteria) : boolean
Some API resources contain many subresources which makes the creation of a single controller class complicated and hard to maintain. This method will forward the request to a another controller by checking the provided criteria.
Example:
$criteria = array( 'items' => 'OrdersItemsAttributesApiV2Controller', 'totals' => 'OrdersTotalsApiV2Controller' );
Notice: Each controller should map a direct subresource and not deeper ones. This way every API controller is responsible to map its direct subresources.
| Throws |
|
|---|
arrayAn array containing the mapping criteria.
booleanReturns whether the request was eventually mapped.
_minimizeResponse(array &$response)
APIv2 supports the GET "fields" parameter which enables the client to select the exact fields to be included in the response. It does not support nested fields, only first-level.
You can provide both associative (single response item) or sequential (multiple response items) arrays and this method will adjust the links accordingly.
arrayPassed by reference, it will be minified to the required fields.
_paginateResponse(array &$response, $p_totalItemCount = null)
One of the common functionalities of the APIv2 is the pagination and this can be easily achieved by this function which will update the response with the records that need to be returned. This method will automatically set the pagination headers in the response so that client apps can easily navigate through results.
arrayPassed by reference, it will be paginated according to the provided parameters.
_prepareResponse()
This method will prepare default attributes of the API responses. Further response settings must be set explicitly from each controller method separately.
Not available to child-controllers (private method).
_searchResponse(array &$response, string $p_keyword)
Normally the best way to filter the results is through the corresponding service but some times there is not specific method for searching the requested resource or subresource. When this is the case use this method to filter the results of the response before returning them back to the client.
| Throws |
|
|---|
arrayContains the response data to be written.
stringThe keyword to be used for the search.
_setJsonValue(string $jsonString, string $property, string $value) : string
stringThe json formatted string which should be updated.
stringThe name or key of the property which should be updated.
stringThe new value which should be set.
stringThe updated json formatted string.
_setPaginationHeader(integer $p_currentPage, integer $p_itemsPerPage, integer $p_totalItemCount)
Useful for GET responses that return multiple items to the client. The client can use the links to navigate through the records without having to construct them on its own.
| link |
Not available to child-controllers (private method). |
|---|---|
| Throws |
|
integerCurrent request page number.
integerThe number of items to be returned in each page.
integerTotal number of the resource items.
_setRateLimitHeader()
There is a cache file that will store each user session and provide a security mechanism that will protect the shop from DOS attacks or service overuse. Each session will use the hashed "Authorization header" to identify the client. When the limit is reached a "HTTP/1.1 429 Too Many Requests" will be returned.
Headers: X-Rate-Limit-Limit >> Max number of requests allowed. X-Rate-Limit-Remaining >> Number of requests remaining. X-Rate-Limit-Reset >> UTC epoch seconds until the limit is reset.
Important: This method will be executed in every API call and it might slow the response time due to filesystem operations. If the difference is significant then it should be optimized.
Not available to child-controllers (private method).
| Throws |
|
|---|
_sortResponse(array &$response)
This method supports nested sort values, so by providing a "+address.street" value to the "sort" GET parameter the records will be sort by street value in ascending order. Method supports sorting up to 5 fields.
Important #1: This method has some advantages and disadvantages over the classic database sort mechanism. First it does not need mapping between the API fields and the database fields. Second it does not depend on external system code to sort the response items, so if for example a domain-service does not support sorting the result can still be sorted before sent to the client. The disadvantages are that it will only support a predefined number of fields and this is a trade-off because the method should not use the "eval" function, which will introduce security risks. Furthermore it might be a bit slower than the database sorting.
Important #2: This method is using PHP's array_multisort which by default will sort strings in a case sensitive manner. That means that strings starting with a capital letter will come before strings starting with a lowercase letter. http://php.net/manual/en/function.array-multisort.php
Example: // will sort ascending by customer ID and descending by customer company api.php/v2/customers?sort=+id,-address.company
arrayPassed by reference, contains an array of the multiple items that will returned as a response to the client.
_validateRequest()
This method will validate the request headers, user authentication and other parameters before the controller proceeds with the response.
Not available to child-controllers (private method).
| Throws |
|
|---|
_writeResponse(array $response, integer $p_statusCode = 200)
Use this method to write a JSON encoded, pretty printed and unescaped response to the client consumer. It is very important that the API provides pretty printed responses because it is easier for users to debug and develop.
IMPORTANT: PHP v5.3 does not support the JSON_PRETTY_PRINT and JSON_UNESCAPED_SLASHES so this method will check for their existance and then use them if possible.
arrayContains the response data to be written.
integer(optional) Provide a custom status code for the response, default 200 - Success.
delete()
| apiVersion |
2.1.0 |
|---|---|
| apiName |
DeleteProduct |
| apiGroup |
Products |
| apiDescription |
Removes a product record from the database. To see an example usage take a look at
|
| apiExample |
{curl} Delete Product With ID = 24 curl -X DELETE --user admin@shop.de:12345 http://shop.de/api.php/v2/products/24 |
| apiSuccessExample |
{json} Success-Response { "code": 200, "status": "success", "action": "delete", "resource": "Product", "productId": 24 } |
| apiError |
400-BadRequest Product record ID was not provided in the resource URL. |
| apiErrorExample |
Error-Response HTTP/1.1 400 Bad Request { "code": 400, "status": "error", "message": "Product record ID was not provided in the resource URL." } |
get()
| apiVersion |
2.6.0 |
|---|---|
| apiName |
GetProduct |
| apiGroup |
Products |
| apiDescription |
Get multiple or a single product records through a GET request. This method supports all the GET parameters
that are mentioned in the "Introduction" section of this documentation. To see an example usage take a look at
|
| apiExample |
{curl} Get All Products curl -i --user admin@shop.de:12345 http://shop.de/api.php/v2/products {curl} Get Product With ID = 24 curl -i --user admin@shop.de:12345 http://shop.de/api.php/v2/products/24 |
| apiError |
404-NotFound Product does not exist. |
| apiErrorExample |
Error-Response HTTP/1.1 404 Not Found { "code": 404, "status": "error", "message": "Product does not exist." } |
post()
| apiVersion |
2.6.0 |
|---|---|
| apiName |
CreateProduct |
| apiGroup |
Products |
| apiDescription |
Creates a new product record in the system. To see an example usage take a look at
|
| apiParamExample |
{json} Request-Body { "isActive": false, "sortOrder": 0, "orderedCount": 1, "productModel": "ABC123", "ean": "", "price": 16.7983, "discountAllowed": 0, "taxClassId": 1, "quantity": 998, "weight": 0, "shippingCosts": 0, "shippingTimeId": 1, "productTypeId": 1, "manufacturerId": 0, "quantityUnitId": 0, "isFsk18": false, "isVpeActive": false, "vpeID": 0, "vpeValue": 0, "name": { "en": "test article", "de": "Testartikel" }, "description": { "en": "[TAB:Page 1] Test Product Description (Page 1) [TAB: Page 2] Test Product Description (Page 2)", "de": "[TAB:Seite 1] Testartikel Beschreibung (Seite 1) [TAB:Seite 2] Testartikel Beschreibung (Seite 2)" }, "shortDescription": { "en": " Test product short description. ", "de": "Testartikel Kurzbeschreibung " }, "keywords": { "en": "", "de": "" }, "metaTitle": { "en": "", "de": "" }, "metaDescription": { "en": "", "de": "" }, "metaKeywords": { "en": "", "de": "" }, "infoUrl": { "en": "", "de": "" }, "urlKeywords": { "en": "test-article", "de": "Testartikel" }, "checkoutInformation": { "en": "", "de": "" }, "viewedCount": { "en": 0, "de": 32 }, "images": [ { "filename": "artikelbild_1_1.jpg", "isPrimary": false, "isVisible": true, "imageAltText": { "en": "", "de": "" } }, { "filename": "artikelbild_1_2.jpg", "isPrimary": false, "isVisible": true, "imageAltText": { "en": "", "de": "" } }, { "filename": "artikelbild_1_3.jpg", "isPrimary": false, "isVisible": true, "imageAltText": { "en": "", "de": "" } } ], "settings": { "detailsTemplate": "standard.html", "optionsDetailsTemplate": "product_options_dropdown.html", "optionsListingTemplate": "product_options_dropdown.html", "showOnStartpage": false, "showQuantityInfo": true, "showWeight": false, "showPriceOffer": true, "showAddedDateTime": false, "priceStatus": 0, "minOrder": 1, "graduatedQuantity": 1, "onSitemap": true, "sitemapPriority": "0.5", "sitemapChangeFrequency": "daily", "propertiesDropdownMode": "dropdown_mode_1", "startpageSortOrder": 0, "showPropertiesPrice": true, "usePropertiesCombisQuantity": false, "usePropertiesCombisShippingTime": true, "usePropertiesCombisWeight": false }, "addonValues": { "productsImageWidth": "0", "productsImageHeight": "0" } } |
| apiParam |
{Boolean} isActive Whether the product is active. {Number} sortOrder The sort order of the product. {Number} orderedCount How many times the product was ordered. {String} productModel Product's Model. {String} ean European Article Number. {Number} price Product's Price as float value. {Number} discountAllowed Percentage of the allowed discount as float value. {Number} taxClassId The tax class ID. {Number} quantity Quantity in stock as float value. {Number} weight The weight of the product as float value. {Number} shippingCosts Additional shipping costs as float value. {Number} shippingTimeId Must match a record from the shipping time entries. {Number} productTypeId Must match a record from the product type entries. {Number} manufacturerId Must match the ID of the manufacturer record. {Number} quantityUnitId Must match the ID of the quantity unit record. {Boolean} isFsk18 Whether the product is FSK18. {Boolean} isVpeActive Whether VPE is active. {Number} vpeID The VPE ID of the product. {Number} vpeValue The VPE value of the product as float value. {Object} name Language specific object with the product's name. {Object} description Language specific object with the product's description. {Object} shortDescription Language specific object with the product's short description. {Object} keywords Language specific object with the product's keywords. {Object} metaTitle Language specific object with the product's meta title. {Object} metaDescription Language specific object with the product's meta description. {Object} metaKeywords Language specific object with the product's meta keywords. {Object} infoUrl Language specific object with the product's info url (e.g. manufacturer homepage). infoUrl replaces url, which is deprecated {Object} urlKeywords Language specific object with the product's url keywords. {Object} checkoutInformation Language specific object with the product's checkout information. {Object} viewedCount Language specific object with the product's viewed count. {Array} images Contains the product images information. {String} images.filename The product image file name (provide only the file name and not the whole path). {Boolean} images.isPrimary Whether the image is the primary one. {Boolean} images.isVisible Whether the image will be visible. {Object} images.imageAltText Language specific object with the image alternative text. {Object} settings Contains various product settings. {String} settings.detailsTemplate Filename of the details HTML template. {String} settings.optionsDetailsTemplate Filename of the options details HTML template. {String} settings.optionsListingTemplate Filename of the options listing HTML template. {Boolean} settings.showOnStartpage Whether to show the product on startpage. {Boolean} settings.showQuantityInfo Whether to show quantity information. {Boolean} settings.showWeight Whether to show the products weight. {Boolean} settings.showPriceOffer Whether to show price offer. {Boolean} settings.showAddedDateTime Whether to show the creation date-time of the product. {Number} settings.priceStatus Must match a record from the price status entries. {Number} settings.minOrder The minimum order of the product. {Number} settings.graduatedQuantity Product's graduated quantity. {Boolean} settings.onSitemap Whether to include the product in the sitemap. {String} settings.sitemapPriority The sitemap priority (provide a decimal value as a string). {String} settings.sitemapChangeFrequency Possible values can contain the {String} settings.propertiesDropdownMode Provide one of the following values: "" >> Default - all
values are always selectable, {Number} settings.startpageSortOrder The sort order in the startpage. {Boolean} settings.showPropertiesPrice Whether to show properties price. {Boolean} settings.usePropertiesCombisQuantity Whether to use properties combis quantitity. {Boolean} settings.usePropertiesCombisShippingTime Whether to use properties combis shipping time. {Boolean} settings.usePropertiesCombisWeight Whether to use properties combis weight. {Object} addonValues Contains some extra addon values. {String} addonValues.productsImageWidth The CSS product image width (might contain size metrics). {String} addonValues.productsImageHeight The CSS product image height (might contain size metrics). |
| apiSuccess |
(Success 201) Response-Body If successful, this method returns a complete Product resource in the response body. |
| apiError |
400-BadRequest The body of the request was empty. |
| apiErrorExample |
Error-Response HTTP/1.1 400 Bad Request { "code": 400, "status": "error", "message": "The body of the request was empty." } |
put()
| apiVersion |
2.1.0 |
|---|---|
| apiName |
ProductCategory |
| apiGroup |
Products |
| apiDescription |
Use this method to update an existing product record. Take a look in the POST method for more detailed
explanation on every resource property. To see an example usage consider
|
| apiSuccess |
Response-Body If successful, this method returns the updated Product resource in the response body. |
| apiError |
400-BadRequest Product data were not provided. |
| apiErrorExample |
Error-Response (No data) HTTP/1.1 400 Bad Request { "code": 400, "status": "error", "message": "Product data were not provided." } |
| todo |
Error status code on not found entries should be 404 and not 400. |
DEFAULT_PAGE_ITEMS
| var |
|---|
DEFAULT_CONTROLLER_NAME
| var |
|---|
DEFAULT_RATE_LIMIT
| var |
|---|
DEFAULT_RATE_RESET_PERIOD
| var |
|---|
productJsonSerializer : \ProductJsonSerializer
productListItemJsonSerializer : \ProductListItemJsonSerializer
subresource : array
| var |
|---|
array
api : \Slim\Slim
| var |
|---|
\Slim\Slim
uri : array
Example: URI - api.php/v2/customers/73/addresses CODE - $this->uri[1]; // will return '73'
| var |
|---|
array