Thursday, January 5, 2017

Interfaces – PHP OOP Tutorial

courtasy : http://jaskokoyn.com/2013/06/11/interfaces/


In this tutorial, you’ll learn how to create interfaces and why you should use them. They are very similar to abstract classes. At the end of this tutorial, we’ll discuss the differences and the benefits of each one.
We’ll be creating something similar to our recipe and cookie class in our abstraction tutorial.

Creating Interfaces

Create a file called index.php and add this bit of code.
Create a folder called interfaces and then create the recipe.interface.php file and cookie.interface.php file.  Let’s first create the Recipe interface.
Here’s what our Recipe interface looks like.
To create an interface you use the interface keyword. This keyword tells PHP that you’re creating an interface. An interface can not contain properties, but it can contain constants and methods. Any method you create in the interface can not contain any concrete code inside of it. All methods created must be public. You’ll also notice we don’t have to repeat the interface keyword before every method.
Now, that we’ve created an interface. Let’s create the cookie class.
Inside the cookie.interface.php file, add this bit of code.
You’ll notice that we’re not using the keyword extends to use the interface. Instead, you have to use the implements keyword in order to use an interface. Just like abstract classes, you must define any methods defined in the interface in your class.
Just like abstract classes, you CAN NOT instantiate interfaces. So, in our index.php file, we instantiate the cookie class. This is how you create interfaces.
Interfaces can be useful as they can be used as an empty shell or template for classes that need logic structured for them.

Interfaces vs Abstract Classes

Interfaces and abstract classes are pretty similar. They both help create templates for classes that need them. So, which one do you use and what are the major differences? Here a couple of things to know about each one.
  1. Methods in abstract classes can be defined abstract or just a regular method. If a method is abstract, then that method must be defined in the class that extends it. In interfaces,ALL methods are abstract, therefore all methods must be defined in the class that implements them.
  2. You’re allowed to define your methods as public, private, or protected in abstract classes. In interfaces, ALL methods MUST be public.
  3. In abstract classes, you’re allowed to create methods and properties with values and concrete code in them as long as they’re not defined as abstract. Interfaces CAN NOT contain properties and methods CAN NOT have a body.
  4. A class can only extend 1 abstract class, but a class can implement an infinite amount of interfaces even if the interfaces don’t relate to one another.
  5. You have the option to override methods in an abstract class, but you MUST override ALL methods in an interface.
As I stated earlier, you can have a class inherit multiple interfaces. To do this, you separate each interface with a comma. Let’s say I had an interface named business. Here’s how our cookie class would implement both the recipe and business interface.

Conclusion

As you can see, interfaces are a bit more stricter than abstract classes. Interfaces are meant to be used  just as a template or empty shell for other classes to follow a certain logic. Abstract classes are lenient and can contain some helpful methods and properties for any class that extends it. It’s up to you to choose which one best suits your project. In most cases, you won’t find yourself using interfaces or abstract classes often. For more information on interfaces, then go here.

Wednesday, January 4, 2017

Programmatically (manually) creating simple Magento product


Programmatically (manually) creating simple Magento product


Programmatically manually creating
In a development process, you often need some testing data you can use. Magento supplies you with it’s default Sample Data that contains some products. Thing is, they’re not of much use if you have some custom attributes added to your products, if you create your own attribute set, or a product type.
For this, you’ll need to add some products yourself.
Sometimes, doing so in the administration is enough, but it gets painful when you need to add multiple products, or if you’re still developing some feature, and making changes on the fly.
This problem can be easily solved by adding products programmatically.
I’ll show you an example on how to add a simple product this way. You could modify this code a bit, and make it work for other product types, or even use it as an import script.
You can call this through an observer, set is as a controller action, or cheat and call it from a view file, whichever you think is best. Just pay attention, that if you observe some event, don’t use the ones that get called on every controller action. Or, if you do, be sure to check if the product with the same SKU already exists, by loading product’s ID by SKU before the attempt to create it. For this, you can use the ‘if’ check on lines 4 and 49 in the code example below.
If you don’t do that, you’ll get SQL errors line the following one:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '193-1' for key 'UNQ_CATALOGINVENTORY_STOCK_ITEM_PRODUCT_ID_STOCK_ID'
Let’s get to the code I’m talking about.
<?php
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product');
//    if(!$product->getIdBySku('testsku61')):
 
try{
$product
//    ->setStoreId(1) //you can set data in store scope
    ->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
    ->setAttributeSetId(9) //ID of a attribute set named 'default'
    ->setTypeId('simple') //product type
    ->setCreatedAt(strtotime('now')) //product creation time
//    ->setUpdatedAt(strtotime('now')) //product update time
 
    ->setSku('testsku61') //SKU
    ->setName('test product21') //product name
    ->setWeight(4.0000)
    ->setStatus(1) //product status (1 - enabled, 2 - disabled)
    ->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
    ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
    ->setManufacturer(28) //manufacturer id
    ->setColor(24)
    ->setNewsFromDate('06/26/2014') //product set as new from
    ->setNewsToDate('06/30/2014') //product set as new to
    ->setCountryOfManufacture('AF') //country of manufacture (2-letter country code)
 
    ->setPrice(11.22) //price in form 11.22
    ->setCost(22.33) //price in form 11.22
    ->setSpecialPrice(00.44) //special price in form 11.22
    ->setSpecialFromDate('06/1/2014') //special price from (MM-DD-YYYY)
    ->setSpecialToDate('06/30/2014') //special price to (MM-DD-YYYY)
    ->setMsrpEnabled(1) //enable MAP
    ->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
    ->setMsrp(99.99) //Manufacturer's Suggested Retail Price
 
    ->setMetaTitle('test meta title 2')
    ->setMetaKeyword('test meta keyword 2')
    ->setMetaDescription('test meta description 2')
 
    ->setDescription('This is a long description')
    ->setShortDescription('This is a short description')
 
    ->setMediaGallery (array('images'=>array (), 'values'=>array ())) //media gallery initialization
    ->addImageToMediaGallery('media/catalog/product/1/0/10243-1.png', array('image','thumbnail','small_image'), false, false) //assigning image, thumb and small image to media gallery
 
    ->setStockData(array(
                       'use_config_manage_stock' => 0, //'Use config settings' checkbox
                       'manage_stock'=>1, //manage stock
                       'min_sale_qty'=>1, //Minimum Qty Allowed in Shopping Cart
                       'max_sale_qty'=>2, //Maximum Qty Allowed in Shopping Cart
                       'is_in_stock' => 1, //Stock Availability
                       'qty' => 999 //qty
                   )
    )
 
    ->setCategoryIds(array(3, 10)); //assign product to categories
$product->save();
//endif;
}catch(Exception $e){
Mage::log($e->getMessage());
}
We’re setting this product in ‘Default Values‘ scope. You can uncomment the code on line 5 to set product data for a specific store. For example, you could do this:
...
    ->setMetaTitle('test meta title 2')
    ->setMetaKeyword('test meta keyword 2')
    ->setMetaDescription('test meta description 2')
    ->setStoreId(2)
    ->setMetaTitle('Some other meta title')
    ->setMetaKeyword('Some other meta keyword')
    ->setMetaDescription('Some other meta description')
$product->save();
The code above will set different meta values in store with an ID of 2.
You can find all the values you are able to set for the product by logging the post data on product save. I’m thinking of saveAction in the ProductController that gets called from Magento administration when you’re saving a product.
app/code/core/Mage/Adminhtml/controllers/Catalog/ProductController.php
public function saveAction()
{
    $storeId        = $this->getRequest()->getParam('store');
    $redirectBack   = $this->getRequest()->getParam('back', false);
    $productId      = $this->getRequest()->getParam('id');
    $isEdit         = (int)($this->getRequest()->getParam('id') != null);
 
    $data = $this->getRequest()->getPost();
    if ($data) {
        Mage::log($data);
Just add the last line to the file. Be sure to delete it when you’re done developing, though. This will get you an array of data you can save. For example for setting [meta_title], you’ll use a magic method setMetaTitle(‘somevalue’).
Note: This is a revamp of an article originally written in July 2009.