Magebasehttp://magebase.com
Magento Tutorials, Tips and Extensions - For Developers by DevelopersWed, 29 Nov 2017 09:06:37 +0000en-UShourly1https://wordpress.org/?v=4.9.8Magento 2 SEO: Default Settings General Outlinehttp://feedproxy.google.com/~r/magebase/~3/lOSPoQPQ6XU/
http://magebase.com/magento-tutorials/magento-2-seo-default-settings-general-outline/#commentsTue, 06 Jun 2017 17:24:34 +0000http://magebase.com/?p=1869SEO is important if you want organic traffic from the search engines to your Magento store. But how do you set it up properly in Magento 2? Read this article to find out.

]]>A typical online store cannot manage properly without search engine optimization. On-page optimization should never be neglected in favor of affiliate links and citations (off-page optimization). The biggest advantage of on-page optimization is that it is something you can fully control and manage.

Magento 1.X is not as perfect as it could be regarding SEO. Many pitfalls weren’t taken into consideration at all. The users needed something more professional, stable, and flexible. That’s how Magento 2 appeared. The second version of Magento drastically differs from the first one. The developers have taken into account previous failures and omissions, transforming them into definite advantages. In this article, we are going to reveal Magento 2 SEO secret settings to prepare you for easy switching to the newer, better version.

Basic SEO Aspects of Magento 2

Products And Meta Tags

We cannot help but bring to the attention the importance of meta tags for your products. The website needs them to get a high degree of competitiveness, have a relevant ranking, and be attractive in a search engine results page (SERP). Naturally, that product pages are particularly important for e-commerce websites. So, our choice is not accidental.

The new version of Magento means the new features. You will definitely appreciate the feature we are going to talk about next. Fields Auto-Generation. It provides templates for product meta data on a global level.

How to get the feature settled? Go to Stores, press on Configuration, and choose Catalog. The new feature Product Fields Auto-Generation appears. It is a time-saving tool, which is an essential element in the case of multiple products. But it is not as flawless as one may initially think. The main problems are:

Unchangeable auto-generated fields. They cannot be fixed for a particular product or subcategory. For example, you can’t change a concrete field for a concrete category like for women or children shoes, etc.

Non-retrospective adjustments. This means they can be applied only to the new products, but not to the already existing ones.

Limited possibilities due to three placeholders/fields only.

«Description» field is not suitable for a typical Meta Description Mask because the allowed number of characters is too small. For example, it offers you the number of 25 characters as the most optimal one, while asking to limit the maximum amount of characters to 200 characters. As practice shows, most stores have quite long product descriptions.

Product Fields Auto-Generation feature has promising prospects. For now, it is a little bit raw, simple, and insufficiently considered. Perhaps, the future versions of Magento will allow their customers to get the Fields Auto-Generation option, which is not so fixed and limited.

As an option, you can still add meta tags straight from the product page settings. Open Products, choose Basic Settings and press on Search Engine Optimization. But be ready to spend a lot of time by doing this if you have more than several products. Non-automated standard one-by-one product customization is not an option for a huge number of products.

Home Page And Meta Tags

The first thing you have to do when opening Magento 2 is the Home Page customization. This version of the program (as well as the previous one) sets the default main page title to the Home Page. So, you need to go to Content and open Pages – Home Page- Page Information.

Products and SEO-Friendly URLs

Magento 2 version as well as Magento 1 version offers you the ability to change and edit URLs whenever you need it. The only difference is how to do this. To edit URL in Magento 2 version, go to Product – Basic Settings – Search Engine Optimization.

This very simple but very useful SEO technique helps the indexation process of your website.

Categories And SEO-Friendly URLs

To install meta data for categories, open Stores – Configuration – General – Design – HTML Head. For category level, it will be Products – Categories – General Information. Here you can specify a needed URL.

Images

One of the most critical rules you should always remember is that optimization of images influences the speed of the website drastically. That will, in turn, influence the ranking of the website. And the faster website means the higher ranking. Unfortunately, nor Magento 1 neither Magento 2 has optimal tools for proper image optimization. However, there are several really good extensions for Magento 2, which work perfectly for any image optimization. Image compression really matters in website ranking. So, never use images, which are too heavy if you want your online store to function fast and properly. Sometimes, compression can worsen the quality of the images. So, make sure you have the right extension package installed. Then, go to Stores – Configuration – Advanced – Developer – Image Processing Settings. Change PHP GD2 to extension package and save. Then, go to System and press on Cache Management. The last but not the list is Flush Catalog Images Cache. Just click the button.

And don’t forget to delete «Magento Commerce» sign or to change it to something else on your logo image. You can easily do it in Stores – Configuration – General – Design – HTML Head – Header. Choose «Logo Image Alt» and type your store name or whatever you want.

Title Tags: Prefixes And Suffixes

In the second version of Magento users can important information (for example, a business name) to the title tags. The information appears at the beginning or the end of the tag on all pages of the website. To set this feature, go to Stores – Configuration – General – Design – HTML Head.

Unique Content in Magento 2

In terms of unique and duplicate content problems, Magento 2 has brand new tools and new solutions. A case in point is canonical tags. Here we have canonical tags for products and categories separately.

Yes, Magento 1.X has similar options. But the new version provides canonical tags for filtered and sorted pages as well.

BUT:

When choosing Canonical Link Meta Tag For Categories, a paginated result will be counted too.

Canonical tags and no index tags can’t be used together.

Category Path And Product URLs

In Magento 2 you can select or deselect the feature of showing or not showing the category path in product URLs. For this, go to Stores – Configuration – Catalog – Search Engine Optimization. This function is good for managing your web indexing. Moreover, it has several variants of realization:

Not adding a category path to the product URLs. This automatically means the elimination of any possible duplicates.

Adding a category path to page addresses, while enabling canonical tags. The probability of duplicates.

Enabling of both canonical tags and category paths. This means that there will not be any category indication and the product page will get a canonical pointing to itself. At the same time, the URLs will get their own category paths and will be available from any category you add.

Web Indexing

Robots.txt

In the Magento version, you can edit robot.txt files from the admin panel directly. Go to Stores – Configuration – Catalog – Design and open Search Engine Robots. Easy, fast, and handy.

Thus, in this version of Magento, you can use the default settings, or you can set and save your own instructions.

Meta Robots

In Magento 2 default meta robots correspond to Index, Follow. This fully applies to Google. But it can’t be customized on a concrete page separately.

HTML Sitemap

There is no HTML Sitemap for this version of Magento. Customization or extension is needed. It is recommended to get a must have HTML Sitemap for Magento 2 for several reasons. Firstly, you will get a clear and detailed structure of your website. And secondly, it drastically increases chances for your website to get noticed by search engines. Don’t forget that not only your customers but also web crawlers can read your HTML Sitemap. So, never omit a chance to install HTML Sitemap on your website. It is one more chance for the website to be indexed and crawled in full. Thus, it is a great opportunity for hundreds of your product pages to be reached.

XML Sitemap

Contrary to the HTML Sitemap, XML Sitemap is more progressive and developed in the second version of Magento. A bunch of new features, extra high standards, and new ways to «attract» search engines. All of these refer to Magento 2 XML Sitemap settings.

This feature of Magento 2 is the most upgraded and updated. It has plenty of additional settings, which can be found in Stores – Configuration – Catalog –XML Sitemap.

Now you can add all images automatically and submit your XML Sitemap URL to Robots.TXT. You can also choose the preferable amount of pages for one file and increase the maximum size of the file.

BUT…

Everything is not so ideal. There are couples of drawbacks, which definitely deserve your attention. So, here is the bad part:

You can’t choose the type of a product (configurable, bundle, etc.) to add it to your Sitemap. This happens because of automatic product selection. The program reads each version of a product as a simple product. For example, you need to add a configurable type of a product. But it consists of several versions. The program will automatically read each version of a product as a single product and will include it into the sitemap.

You can’t add or delete concrete pages, in case you need it.

The fact that you can add images to your XML Sitemap is great. But what if you have any other type of the file? When it comes to other formats like Word, PDF, Excel, etc., you can add them manually only.

Remember, that sitemap is a helping hand for your website. It is a way out when trying to get your page to be noticed and crawled by search engines. It helps to reach your potential customers fast and easy. Sitemaps matter when it comes to visibility and optimization of your online store.

Talking about XML Sitemaps, Magento 2 comes with really qualitative, functional, useful, and enhanced innovations and improvements. A list of SEO settings, mentioned above, is definitely a step forward for Magento and SEO marketing, in general. Here we appreciate both usability and functionality. XML Sitemaps «attract» search engine crawlers, helping them to stand out and understand, which URLs should be indexed first.

Additional Features Of Magento 2

Product And Category URLs Suffixes

Magento 2 claims that the products and categories can get different suffixes. Practically, it is not convenient. Most users prefer identical URLs for each website. If you choose different suffixes, you can cause a 404 page. All the changes are retrospective. After all changes, everything you get is 404 error from the former page. So, be careful when making any changes, especially significant.

Microdata

This is a completely new feature by Magento 2. Now each product page receives microdata by default. You get automatically included all important tags.

Google Adwords

Google Adwords performance has never been easier before. Magento 2 has drastically simplified the implementation process. Go to Stores – Configuration – Google API – Google Adwords. In the open window, you will see a whole set of basic parameters like Format and Conversion ID.

Google Analytics

Magento has worked with Google Analytics features and created one more handy tool in the new version. So, what does it do? It provides you with new ways of adding a Google Analytics tracking code to the store. It’s pretty straight forward. To activate the tool, go to Stores – Configuration – Sales – Google API – Google Analytics.

You have to open Admin – Tracking Info (GA Account), copy your Tracking ID and add it to Google Analytics.

How to do: Product – Advanced Settings – Product View Optimization.

If you don’t want to work with Google Analytics, or you want to save some time, you can always apply to an AB testing tool. It is not available on Magento 2 yet, but you can easily find it on Magento 1.X.

Brief Overview of Magento 2 SEO Settings

The new version of Magento, which is Magento 2, has a long list of brand new and old but updated features and settings. Among the most effective and considerable settings are meta tags for products and categories, title tags prefixes and suffixes, image optimization, canonical tags, robots.txt, meta robots, XML Sitemap, microdata, category path in product URLs, Google Analytics and Adwords aspects. This huge work was done to make positive changes in SEO and marketing, in general. Some of the features have already become favorite ones. Others are still very raw and primitive. Most of them are not flexible enough to be successfully implemented and used in real stores for real products.

Generally, Magento 2 has improved performance and scalability, simplifying external integrations at the same time.

We hope that this article was quite interesting and useful for you. And we hope you will get a good experience with your own Magento 2 SEO strategy. Try out one of the most popular e-commerce platforms in the 21st century by yourself. Which side are you going to take – the lovers or the haters of Magento 2?

]]>http://magebase.com/magento-tutorials/magento-2-seo-default-settings-general-outline/feed/4http://magebase.com/magento-tutorials/magento-2-seo-default-settings-general-outline/Adding Openexchangerates Currency Conversion Service to Magentohttp://feedproxy.google.com/~r/magebase/~3/bSfeFEj9Mvc/
http://magebase.com/magento-tutorials/adding-openexchangerates-currency-conversion-service-to-magento/#commentsWed, 26 Feb 2014 20:03:12 +0000http://magebase.com/?p=1831If your Magento store depends on up to date currency information, you would have noticed that the built in Webservicex service hasn't been working for some time now. There are a few 'hacks' around that use Yahoo and Google Finance services but these may violate their T&Cs so we offer another alternative solution using Openexchangerates.org.

]]>Most Magento users who have multiple currencies showing on their site would have noticed that the built in Webservicex currency service stopped working some time ago (towards the end of 2013).

After searching around for a while we found an article that shows how to add the Yahoo Finance currency conversion service to Magento, however, it transpires that this violates Yahoo’s T&C so it is really not an option. Likewise, Google’s currency conversion service has been discontinued. Therefore, what options are left?

After some more searching, we discovered Openexchangerates which offers both a free and several levels of premium services. The free option allows for up to 1000 API requests per month which we thought was more than enough for the standard use case in Magento. Let’s say a month has 31 days, this would allow for about 32 requests per day which means that you could have the currency service updating your site every 45 minutes and not hit the monthly access limit. So, sign up for a free account and get your App Id.

All this is good news so we created a quick extension that adds this service to Magento.

Assuming our audience is comfortable with creating an extension for Magento, we’ll just showcase the relevant code here and leave you to assembling it into an installable module.

First we want to define the module namespace, so we called this Magebase_Openexchangerates. We will just create Helper, Model and etc folders as illustrated in the image to the right.

Our extension will have a couple of system configuration options which are accessible from System > Configuration > General > Currency, the App Id and the connection timeout, so our system.xml looks like this:

You will notice in the global node we define our new exchange rate service to Magento. The name will show up in the service selection drop-downs and the model will be our new currency exchange class that will handle the retrieval and processing of the currency rates from Openexchangerates’ API.

The Openexchangerates API documentation is pretty clear and there are good examples of the various use cases and premium features, however, we are only going to consider the API call provided by the free access which retrieves all available rates in one hit by simply calling http://openexchangerates.org/api/latest.json?app_id=YOUR_APP_ID. We get data back as JSON so it’s really easy to parse and process further.

To execute our rates retrieval, we have the Model/Currency/Import/Openexchangerates.php file with our class that extends Mage_Directory_Model_Currency_Import_Abstract:

There are a couple of idiosyncrasies with this service in comparison to how the old service was operating. First, we get all rates in one request unless we want to pay for the premium service where we can call the service by passing specific currencies to convert between. Second, the returned rates are all based on the exchange rate against the US dollar. This means that we had to re-think the way we handle this.

Firstly, we retrieve the rates in the class constructor as the class is instantiated at the time the “Import Rates” button is clicked. Then we just cache the rates array from the JSON response in our _rates class property.

Magento then goes through all the configured currencies and calls the _convert($currencyFrom, $currencyTo, $retry=0) method for each individual currency. At this stage, our job is easy and we just look up the currency codes in the array keys. The only thing we need to do is cross-convert the from and to currencies since the rates are based on USD, hence the formula.

And there you have it, enjoy continued automated exchange rate updates for your multicurrency site!

DISCLAIMER:As usual, the code here is provided “as is” and Magebase provides no guarantees of accuracy of the conversion service or faultless performance of the code. Test thoroughly and use at your own peril. If you implement this code on a production site, Magebase disclaims any liability for any loss or damages resulting from the use of this code. Support may be provided in the comments depending on our availability but is not guaranteed.

]]>http://magebase.com/magento-tutorials/adding-openexchangerates-currency-conversion-service-to-magento/feed/7http://magebase.com/magento-tutorials/adding-openexchangerates-currency-conversion-service-to-magento/New Release of magebase DPS extensionhttp://feedproxy.google.com/~r/magebase/~3/S__yFGFSSRQ/
http://magebase.com/magento-articles/updated-paymentexpress-extension-manual/#commentsSat, 06 Jul 2013 16:04:29 +0000http://magebase.com/?p=1794Version 1.5 of magebase DPS Payment Express is now available. Highlights include the new manual, more options and a new home for the code.

Better integration with Magento’s transactions and notifications – PxPost details now appear under Sales > Transactions and Order History.

Beyond the Basics – Advanced Functionality with Fooman DPS Pro
Fooman DPS Pro is a new extension which adds more power and features to your Magento-DPS integration. The extension provides advanced functionality and security features, building on the community magebase DPS Payment Express extension developed by Fooman. The extension is aimed at people running Magento stores with higher order volumes and more advanced set ups.

Highlights

Integrate with Maxmind fraud scoring for peace of mind about orders – if you receive an order with a fraud score over a certain risk threshold, you can automatically hide DPS Payment Express as a payment method, or allow the order to be placed but require it to be manually reviewed and accepted after completing due diligence

Save time by processing customer refunds from the Magento backend- this eliminates the need to log into DPS and process each refund manually. Streamline your refunding process and keep it all within the Magento backend

Encourage repeat business with secure tokenised billing – allow your customers to shop more conveniently and reduce shopping cart abandonment. Customers can tick a box if they would like to securely store their credit card information for their next purchase on your site. The same credit card can then be billed for a future customer purchase on the same site

Accept credit card payments via DPS Web Service, with optional use of the 3D Secure feature for advanced online security. 3D Secure adds an extra checkout step to authenticate a customer credit card password against the issuing bank (using the Verified by Visa and MasterCard SecureCode schemes), if a customer has enabled this security feature. Show your customers that you take online security seriously, and reduce your risk of costly credit card fraud and chargebacks

Accept manual payments using your PxPay account, and automatically send notification emails each time a manual payment is received. This is a quick and easy way to bill custom amounts, and is more cost effective than alternatives such as Paypal

]]>http://magebase.com/magento-articles/updated-paymentexpress-extension-manual/feed/16http://magebase.com/magento-articles/updated-paymentexpress-extension-manual/How to setup Magento for Authorize.net Direct Post Methodhttp://feedproxy.google.com/~r/magebase/~3/K-WdjXalfo0/
http://magebase.com/magento-tutorials/how-to-setup-magento-for-authorize-net-direct-post-method/#commentsFri, 07 Jun 2013 20:31:39 +0000http://magebase.com/?p=1771Configuring Magento for use with the Authorize.net Direct Post Method (DPM) is supposed to be quick and easy and it can be, as long as you aware of a few less than obvious steps.

]]>Authorize.net’s Direct Post Method of payment gateway integration is a great option for Magento sites because it allows for a seamless customer experience while simplifying PCI compliance by keeping all sensitive credit card information off of the Magento server. Configuring Magento for use with Direct Post Method (DPM) is supposed to be quick and easy and it can be as long as you aware of a few less than obvious steps.

Make sure that your Authorize.net account is a “Card Not Present” (CNP) account. You can confirm whether or not your Authorize.net account is setup for CNP transactions by logging in to the Merchant Account Admin and verifying that you have CNP features like Recurring Billing and Fraud Detection Suite listed in the Tools section. If you do not see these options or you get errors like “Transactions of this market type cannot be processed on this system” when attempting to authorize payments, the issue is most likely that the account is setup for card present transactions only. If you are using a test account the easiest solution is to just create a new account and make sure to select Card Not Present.

Make sure to set an MD5-Hash. DPM uses an MD5-Hash as a sort of secret key that is set in in the auth.net merchant admin and the Magento admin to help secure comminication between your magento store and auth.net. If during checkout, after entering credit card information and clicking “Place Order”, you get a pop-up alert saying “Response hash validation failed. Transaction declined.” the problem is most likely that this is not set. Set an MD5-Hash in the Authorize.net merchant admin under Settings > Security Settings > General Security Settings > MD5-Hash. Then enter that same value in the Magento Admin under System > Configuration > Payment Methods > Authorize.net Direct Post > Merchant MD5.

Make sure that your server’s time is set correctly. DPM makes use of a timestamp as a security measure and to help synchronize requests. If the server’s time is incorrect you may receive a pop up stating “Gateway error: This transaction cannot be accepted.” This is a generic error message. To get more specific error information you can go into app/code/core/Mage/Authorizenet/Model/Directpost.php and either log or dump $response in function process() by doing something like var_dump($reponse); die(); to output the response from auth.net. If you get a response code 3 with a response reason code of 97 the timestamp value submitted in x_fp_timestamp is either 15 minutes ahead, or 15 minutes behind in Greenwich Mean Time (GMT) (this is the equivalent of 900 seconds ahead or 900 seconds behind in Coordinated Universal Time, or UTC). You can test your timestamps accuracy using this tool http://developer.authorize.net/tools/responsecode97/ . On linux you can get the server time using the date command. If it is incorrect consider setting up Network Protocol Time by doing soething like this: http://alienlayer.com/install-and-configure-ntp-to-synchronize-the-system-clock-on-centos/

Make sure to set the Gateway URL correctly. For test accounts Test Mode should be set to NO and the Gateway URL should be set to https://test.authorize.net/gateway/transact.dll. For Live accounts this should be chagned to https://secure.authorize.net/gateway/transact.dll

Other than that the configuration is pretty straightforward. In the Magento Admin the Authoize.net Direct Post configuration should look something like this:

I hope this helps get you up and running with this very simple and secure payment method. Please feel free to drop any questions in the comments.

Introduction

Once again, albeit after quite a long gap, we have a new Packt Publishing Magento book for review. Of course, our review is also going to be a give-away so keep reading and we’ll tell you how to enter our competition to win 1 of 5 e-copies of this book.

Author

The author is Allan MacGregor. From the ‘About the Author’ part in the book:

“He is a Magento Certified Developer Plus with four years of Magento experience. He also has a certification in Linux System Administration by IBM. He started working with Magento as a freelance looking for a better framework to build e-commerce solutions, and he is now the Magento Lead Developer at Demac Media (www.demacmedia.com). He’s very passionate about software development in general. He is constantly working with new technologies and frameworks…”

I was pleased to see that the author comes from a practical Magento development background with the added credo of the developer certification as well as being a native english speaker. This reflects throughout the book, as it’s well written and understandable.

Content Overview

Chapter 1 provides a concise yet thorough overview on setting up a development environment for Magento work. The author takes us through installing a LAMP stack from scratch and pointing us to his Vagrant & Chef repository on github for some ready made recipes to automate the chore of creating development server instances.

In chapter 2, the author explains the Magento file and module structures, code pools, routing, Magento’s version of the MVC pattern and events and observers. Then in chapter 3 moves onto the ORM and working with data collections to retrieve data from the Magneto database.

With chapter 4, the book starts to get interesting as we are learning how to develop a custom module. One things to note is that the author uses the older “Mysql4” directory paradigm for resource models instead of the current “Resource” one. The material covers the creation of a customer gift registry module which is useful both from a learning point of view as well as practical. The chosen module functionality allows the author to cover most of the aspects of custom Magento coding such as block, model, resource, helper and controller classes as well as database setup scripts and storing and retrieving your module’s data. Finally, in chapter 5, the admin side is also taken care of. We learn how to create the admin interface for our module.

Chapter 6 talks about the Magento API and the built in API protocols supported. Furthermore it also shows us how to extend the API with methods for our customer gift registry module.

Chapter 7 covers testing your custom code and the strategies for building unit tests. And finally, chapter 8 shows us how to properly package and distribute our module to Magento Connect.

Opinion

Overall, I liked the material covered in this book and it will give you a great introduction to module programming for Magento. The language is clear and easy to read, the code examples cover the topics well and the author and publisher provide a code repository and website for the book material for further follow-up. When I browsed this site, however, a few chapters have not yet been updated with content.

In the past, I’ve had comments about the fact that every Packt publishing book spends a lot of space on setting up and configuring development environments which takes away from material that could possibly be more useful. It is the case here as well that the first chapter is dedicated to this topic. While I understand that it is important to cover these types of topics, at this day and age it would be more prudent to cover this off in some sort of additional materials section or appendix and dedicate the main part of the book to the more ‘juicy’ topics.

That aside, the book will certainly be useful to give Magento novices and Magento developers who have maybe implemented themes and want to expand their expertise to module development, a helping hand in understanding all the procedures and approaches that go into creating custom modules. There is also enough theory about some aspects of the Magento architecture like MVC, collections and eav to give you an idea of the complexity and possibilities in Magento. However, if you are looking for in-depth explanations of those magento sub-systems and how they interact across all the built in modules then you will need to discover this on your own. In other words, this book won’t be able to prepare you, for instance, to pass the Magento Developer Exam. In all fairness, I don’t believe this is the aim of the book either but I feel I need to make this comment just in case someone is wondering.

So, all in all, this is a great book for getting started with Magento module development and will be a handy reference for any Magento developer. It also has handy tips about unit testing, module packaging and distribution and the Magento API that it definitely adds value to intermediate Magento developers. The author has managed to produce a well rounded book that delivers on its promise.

Competition

In order to be in the draw to win one of five available e-copies of this book you will need a Twitter account. please follow the instructions below:

Click on the Tweet button at the top of the article

When the popup appears, please make sure to add the hash-tag: #MagentoPhpDeveloperGuideReview to the end of the pre-set text

]]>http://magebase.com/magento-articles/magento-book-reviews/book-review-magento-php-developers-guide-by-packt-publishing/feed/3http://magebase.com/magento-articles/magento-book-reviews/book-review-magento-php-developers-guide-by-packt-publishing/How to make Magento Extensions work with Composerhttp://feedproxy.google.com/~r/magebase/~3/1NunbCcxqk8/
http://magebase.com/magento-tutorials/how-to-make-magento-extensions-work-with-composer/#commentsMon, 04 Feb 2013 23:12:09 +0000http://magebase.com/?p=1722Following on from our previous post about using Composer with Magento, this article is about how to make Magento extensions installable wich Composer.

]]>This post is about how to make Magento extensions installable wich composer. Please refer to the previous post here on magebase.com on how to do the other part, namely install Magento extensions with composer.

Most packages, which are installable with composer, contain a configuration file named composer.json in the modules root directory. (Well, there are ways around this, but that goes beyond the scope of this post. Check the composer reference if you want more.)

Don’t confuse this composer.json file with the composer.json file in the root directory of the target project, which is called the root composer.json.

Note: If you are providing your extension as a Magento Connect 2.0 package you actually don’t have to create the composer.json file – all required information could already be found in the package archive.

But maybe you don’t want to depend on Magento Connect for distribution, or are hosting your module on github anyway. In those cases it makes a lot of sense to provide a composer.json file with the module.

So generally, when you want to make your Module compatible with composer, your first step would be to create that file. Then you fill in the basic information required for any composer package.

You can call composer.phar validate in the directory, and it will tell you if you forgot anything, or if there is a syntax error in the JSON.

If you are familiar with packaging composer files you might have noticed two unusual things. The first on is the type

"type":"magento-module"

This tells the magento-composer-installer that it is responsible to figure out how to install the thing.

And because the magento-composer-installer actually isn’t part of the composer project, each Magento module has to list it as a dependency:

"require":{
"magento-hackathon/magento-composer-installer":"*"
}

That’s almost everything, except for the…

Mapping from Module to Magento

One difference between any other composer package and Magento modules is that Magento extensions need to be integrated into different parts of the Magento source tree after installation. Module code goes into app/code/codePool/ branch, templates and layout configuration into the app/design/ branch, and so on.

First all the module code is installed into the vendor directory (by composer), and then the step of linking the modules files into the Magento source tree is handled by the magento-composer-installer.

This mapping from the module installation directory into Magento needs to be configured.

Currently the mapping can be specified in three ways:

The modules composer.json file

A Magento Connect 2.0 package.xml file

A modman file

The magento-composer-installer will check for each one in the order specified above, and use the first available option.

composer.json map

To specifying the mapping in the composer.json file, add it to the extra.map list like this:

Each file or directory to be mapped is an array with two records. The first record is the file or directory in the modules source tree, and the second record is the location inside of the Magento source tree.

In the example above the first and second record always are the same, but it doesn’t have to be that way. A map entry could look something like this:

["code","app/code/community/My/Module"]

package.xml map

The mapping in a package.xml will be created for you when you build a regular Magento Connect 2.0 extension package through the Magento admin interface (System > Magento Connect > Package Extensions). There is nothing special about it, as all Magento extensions that conform to the Magento Connect 2.0 format can be installed by the magento-composer-installer automatically.

The Magento Connect 2.0 extension format is the one that is used when packages for Magento 1.5 and newer are created. The older format, for Magento instances up to 1.4, are actually PEAR packages. The reason they aren’t supported by the magento-composer-installer, is the assumption, that any Magento instance for which composer manages the modules will be a current version.

modman map

The tool quickly was widely adopted by Magento developers. This actually was the first mapping option the magento-composer-installer supported, because so many modules on github already came bundled with a modman configuration.

Using this method gives you the added benefit that your module can also be installed using the modman script.

The modman configuration file has to be in the root directory of the module package. The basic format is very simple. Each line lists two file system paths. The one on the left is the source directory in the module code base, the one on the right is the target inside of Magento.

(If there are line breaks in the following list between the two items, that’s a formatting bug):

Once again, most people prefer to use the same structure in the module directory tree as in Magento, but it doesn’t have to (like in our example).

Globbing wildcards are also supported:

app/locale/de_DE/* app/locale/de_DE/

There are some additional features modman offers, like executing scripts when a module is installed, but these other options aren’t supported by the magento-composer-installer and will be silently ignored.

The only additional modman feature for which there currently are plans to incorporate into the installer is @import, which allows including modman files from module subdirectories.

Distribution

To make your module available to the composer-using world, the next step is to add it to the Magento module repository at packages.firegento.com.
And once again, you are presented with a choice:

a) Make it available from github
b) Make it available from Magento Connect

a) github

If your module is available on github, it’s easy to add it to the repository.

The packages from Magento Connect have a composer name prefix composer20/ which makes it pretty easy to recognize them.

By the way, you can add your module to the repository hosted on github and from Magento Connect. This can even be useful.

For example, I update my modules often, but only build new Magento Connect packages once in a while. Users who want to get bug fixes quickly, should configure a dependency on the github module (netzarbeiter/customer-activation).

Users who want the code from Magento Connect just use the according package name instead (connect20/customeractivation).

Wrap up

This turned out to be a longer post then I had expected. But I hope you agree that it’s actually no rocket science. In fact, it’s rather easy. I hope to see all your modules on packages.firegento.com soon, if they aren’t there already.

If you have any questions, please post a comment here. If you encounter an issue, please open an issue on github.

]]>http://magebase.com/magento-tutorials/how-to-make-magento-extensions-work-with-composer/feed/7http://magebase.com/magento-tutorials/how-to-make-magento-extensions-work-with-composer/Composer with Magentohttp://feedproxy.google.com/~r/magebase/~3/Etznq_jqXdM/
http://magebase.com/magento-tutorials/composer-with-magento/#commentsTue, 29 Jan 2013 00:58:05 +0000http://magebase.com/?p=1704The purpose of this post is to introduce a better package and dependency management system for Magento extensions.

]]>The purpose of this post is to introduce a better package and dependency management system for Magento extensions.

It was a few months ago that I first heard of composer. I was surprised I had not stumbled over it earlier – it seems the PHP world is moving forward quickly, but I’m so focused on Magento that I miss some things. What a nice surprise to discover this tool!

Background

Here is a short overview, in case your case is similar to mine, and you aren’t yet familiar with composer.

Composer is a package and dependency manager for PHP libraries. But that’s nothing new; don’t we have PEAR you say? Good point.

Well, PEAR was build using the assumption, that PHP library components would be installed system-wide. As it turns out, this isn’t the best solution. In practice, different projects require different versions of the same libraries. If you upgrade system wide libraries, all dependent projects have to be upgraded, too.

So, composer fixes this issue. It installs required libraries separately for each project.

Also, it makes it very easy to manage package repositories, much easier then managing PEAR channels. Even more, it can install packages from many different sources: GIT and SVN repositories, ZIP and TAR files, and yes, even PEAR channels. The person installing the package doesn’t even need to care where the package comes from.

So where do you get available libraries?

All publicly available packages for composer are listed on packagist.org. But because plugins for applications, which have their own eco-system, should not be listed there, we created a public repository for Magento modules: packages.firegento.com.

How does it work?

Composer uses a configuration file, which lives in a project base directory. The file is named composer.json. This file lists configuration options, for example the minimum-stability, and also the list of packages that should be installed. Also a version, or a version range, can be specified for each package.

Composer will use packagist.org to look where to get the libraries. Because Magento modules aren’t listed there, you will have to add the packages.firegento.org repository to the configuration as follows, and also specify the Magento root directory (more on that below):

Once the composer.json configuration file is created, all that needs to be done is install composer (curl –O http://getcomposer.org/composer.phar) and run it:

php composer.phar install

And that’s all. The listed packages and all their dependencies will be installed in the project.

The place where composer installs the libraries is a directory called vendor.

Should the contents of the composer.json file ever be changed, run

php composer.phar update

and the new configuration will be applied.

That is also how you uninstall a package: you remove it from the require list in the composer.json and run composer.phar update.

Back to Magento

As you probably are aware, Magento modules, in contrast to “usual” PHP libraries, aren’t contained in a single directory within the project. Instead module classes live in the code pool subdirectories, translation files under app/locale, and templates in the respective area, package and theme folders, and so on. For this reason, the files which composer installed under vendor, somehow need to be merged into the Magento directory hierarchy.

After installing a Magento module with composer, all files and directories will be symlinked into the respective targets in the Magento directory tree, very similar how modman does.

There is one little piece of information that is required so composer can do that, and that is the path to the Magento root directory. You will always need to add that to the project composer.json file, too:

{
...
"extra":{
"magento-root-dir":"./htdocs"
}
}

In case you prefer copies to symlinks, no problem: simply set the appropriate config option under extra.magento-deploystrategy:

Each solution partner and each developer have their own preferences, but I think most agree that the second variation is cleaner.

Versioning the project

Preamble: I realize not everybody uses git, but for the sake of simplicity I’ll just refer to git here. Think svn, mercurial or whatever the vcs of your choice is instead if you prefer.

The composer.json file is always included in the git repository. For the vendor directory, it depends – it isn’t always versioned.

When composer.phar install is run, a file composer.lock is created which lists all the packages in the currently installed version. But should this file already exist when the install command is called, then composer will re-create that state in listed in that file. For that reason, it theoretically is enough to version the composer.lock file, and add the vendor folder to the .gitignore list. That is assuming that every package will always remain installable in the future.

To avoid that risk, you might prefer to version the vendor directory after all. You choose.

UPDATE: If you end up versioning the vendor directory, you might want to install packages without the .git subdirectories. Composer offers command line switches to control that behaviour: –prefer-dist and –prefer-source (see the reference).

An composer install –prefer-dist will install the packages without the .git subdirectories, whereas –prefer-source will clone the source repositories, which is useful if you want to do work in the packages, too. Then you can commit straight from the vendor/<package-name> directory.

Wrapping up

If you are interested in making your own Magento modules installable with composer, please refer to the next blog post – coming shortly right here.

As mentioned before, modules can come from many different sources. All the modules on packages.firegento.com are hosted on github, or are Magento Connect 2.0 packages, which also can be installed. The latter can be recognized by the connect20/ prefix to the package name.

It also goes beyond the scope of this introductory post to describe all the possibilities the project composer.json offers, for example how to configure private repositories. A little further information can be found in the magento-composer-installer README, and of course in the excellent composer documentation on http://getcomposer.org/doc/.

The one drawback of composer for Magento (so far) is that it doesn’t handle commercial extensions very gracefully. It would be possible to add a private repository and install from there, but that’s not a real solution. But at least the community modules and other external libraries are taken care of nicely!

]]>http://magebase.com/magento-tutorials/composer-with-magento/feed/36http://magebase.com/magento-tutorials/composer-with-magento/Adding Cache Support to Magento Blockshttp://feedproxy.google.com/~r/magebase/~3/qydolQ_ro44/
http://magebase.com/magento-tutorials/adding-cache-support-to-magento-blocks/#commentsMon, 10 Dec 2012 06:18:32 +0000http://magebase.com/?p=1686Magento offers many handy systems that can be used in day to day custom coding. One such system is the caching system. It is fundamental for performance and every Magento developer should be familiar with it. In this tutorial, we explain how to add caching capabilities to your blocks.

]]>Caching is an essential feature of Magento for maintaining performance. Magento provides a caching mechanism for Layout, Blocks, Collection Data, and Configurations. Normally layout updates, configuration data, etc. remain the same each time a page is loaded. Fetching layout updates from multiple files or loading and merging configuration data from XML files and the database cost significant amounts of execution time. Caching provides a mechanism to prepare and store all this data conveniently so it can quickly be retrieved on page loads to save execution time.

In this tutorial, we will cover how you can prepare your custom blocks for block caching.

In block caching, Magento stores the HTML output of the blocks into its cache and subsequently loads the contents directly from it. By default, Magento uses block cache only for the header, footer and top navigation, as their contents is not frequently changed. However, using caching for other blocks is also possible.

Cache Lifetime

The simplest way of enabling cache for a particular block is to set cache_lifetime data. This can be done through layout XML:

Cache Lifetime is time specified in seconds, which defines the expiration time of the cache. In our example we have defined the cache lifetime as 3600 seconds i.e. 1 hour. So our cache would expire after 1 hour, and then re-generated. If cache lifetime is passed as false, the cache will never expire.

Cache Tags

Additionally to the cache lifetime, we can specify cache tags. Tags are useful to programmatically identify particular cache types. In our example, we will add two cache tags: store and cms_block

Cache Keys

Probably the most important part of preparing your blocks for caching is specifying the cache key. The cache key uniquely identifies each cache item. If a cache key is not specified, Magento uses the block’s name in the layout as the cache key. However, it is a good practice to define a custom cache key when adding cache support to the block.

To define a cache key, we can either add a static value of cache_key through the layout XML similarly to the cache lifetime in the above example or add a data key called cache_key through the _construct() method. A unique static string value is sufficient to define a cache key, however, we should consider a scenario when the block has different output for different stores, themes, etc…

For example, a block can have different HTML output for different themes. If we define a static cache key, it will be the same for any theme. So our cache will store the first rendered output, regardless of the theme. When a theme is changed or used by another website in the same Magento install, the same HTML would be returned from cache. That’s why it’s a good idea to have the cache key depended on the theme, package, store etc.

To create a unique cache key, we should override the method getCacheKeyInfo() in our block class and return an array of cache key parts:

Here, the method returns an array. The first element 'EXAMPLE_BLOCK' is our unique identifier. The second element is the current store id. The third element is 1 if current URL is secure (https://) or 0 if URL is not secure. The fourth element is the theme package name. The fifth element is the theme name for rendering templates. The cache key for the block will be generated using all these array elements.

In our example, the cache key will automatically be changed when:

Customer browse to different store

URL is changed from secure (https://) to unsecure (http://) or vice versa

Theme package is changed by administrator

Theme for templates is changed by administrator

As you can see, the array elements for the cache key should be chosen according to the block’s output for different factors. On some site you may be allowing for a currency or language switcher, or both, so in those cases you will need to add more key elements to create a unique cache key specific to the selected currency and/or language, and so on.

Conclusion

We hope you found this short tutorial useful. We recommend adding block cache support for your blocks, especially if you’re creating custom home page blocks or widgets. It will improve the response of the site considerably. The trick is to be mindful about how to create the unique cache key to avoid strange display behaviour in some scenarios.

]]>Magento Commerce provides incredible flexibility for managing product attributes. Using attribute management interface of admin panel, various types of product attributes can be created and can be added to specific attribute sets and groups. After creating products with values for these attributes, frontend product page automatically displays value of an each attribute.

Magento automatically determines the product attribute’s input type and displays the value accordingly. For example, the “description” attribute has input type as text area, so it displays description value as long text; while the “manufacturer” attribute has input type as combo-box, so it will display the option label for the selected manufacturer value.

Normally, we don’t need to customize this behavior as it automatically handles most of the attributes as expected. But in some cases, we want to change, decorate or add additional information for some attributes. For example, we have created an attribute ‘website’ which is a simple attribute with input type as text box, and it accepts data in URL format. By default, on the product page, the value of this attribute will be displayed as normal text without a hyperlink to the URL. But instead of displaying this value as normal text, it would be nice to display a hyperlink so that a customer can visit that URL by clicking on it. Also, if we wanted to, we could have this URL open in a new tab or window.

For the above cases, Magento provides a way to customize the product attribute rendering process by defining our own product attribute output handler. The output handler is a class method that takes the current attribute output, product and attribute as parameters and returns the final output.

Before going into detail about it, we should understand how Magento renders product attributes. Here are the step-by-step details about this process:

When Mage_Catalog_Helper_Output class is instantiated, it fires an event catalog_helper_output_construct. So any observers observing this event are called when this helper class is instantiated.

The productAttribute() method of Mage_Catalog_Helper_Output class creates the default output of an attribute value according to its type and specification.

After creating the default output, it calls all custom product attribute output handler methods in the same order as they are added. It passes the last output of attribute value, product instance and attribute code as parameters.

Final output returned by the last called handler is returned.

So, we have to add our custom output handler by calling addHandler on the catalog/output helper instance before productAttribute() method is called. As mentioned in step 3, an event catalog_helper_output_construct is fired when catalog/output helper in instantiated. So we can observe this event to add our custom output handler.

We will create a new local module with name Magebase_Extras. Here is the config.xml file for this module:

Here, we have added a configuration to observe the event catalog_helper_output_construct using the addCustomAttributeOutputHandler() method of our Magebase_Extras_Model_Observer class. Now in Magebase_Extras_Model_Observer class we will define the method addCustomAttributeOutputHandler() as below:

When catalog_helper_output_construct is fired from catalog/output helper class, it passes its own instance in the event data with the key ‘helper’. Here, we retrieve that instance from event data and call the addHandler method on it. The first argument we have passed is ‘productAttribute’ because we are adding handler for product attributes. This would be ‘categoryAttribute’ if we want to add a handler for category attributes. The second argument is an instance of the extras/output helper i.e. Magebase_Extras_Helper_Output class.

Now we will create this helper class Magebase_Extras_Helper_Output and add the output handler method:

Here, the productAttribute() method works as a custom output handler for our product attribute. We can similarly define a categotyAttribute() method for our custom output handler to render category attributes. As mentioned in step 5, the productAttribute() method of catalog/output helper class creates the default output of our attribute value. Then it processes all custom handlers. The handler method accepts three parameters: $outputHandler, $outputHtml and $params. $outputHandler is an instance of catalog/output helper itself. $outputHtml is the last created output by previously added handlers. In the case of the first added handler, it is the default Magento output. $params is an array of two elements: ‘product’ containing the current product instance and ‘attribute’ containing the attribute code being rendered.

Custom output handler methods are called for all product attributes rendered. In our case, we wanted to modify the output of our ‘website’ attribute only to format it as a hyperlink. So in our custom output handler method, we have checked if we are currently rendering the ‘website’ attribute by checking the value of $param['attribute']. We have also checked that the product has a value for the ‘website’ attribute.

If both conditions are satisfied, we wrap the last output of the ‘website’ attribute value with HTML code for hyperlinking. Now the product page on the frontend will display the website attribute value as a hyperlink.

The same way can be used for category attributes too by defining categoryAttribute() method as mentioned above.

]]>http://magebase.com/magento-tutorials/quick-tip-creating-custom-product-or-category-attribute-renderers/feed/8http://magebase.com/magento-tutorials/quick-tip-creating-custom-product-or-category-attribute-renderers/MageBase_NewZealand – your ideas?!http://feedproxy.google.com/~r/magebase/~3/3fULt3XYAio/
http://magebase.com/magento-articles/magebase_newzealand-your-ideas/#commentsTue, 25 Sep 2012 10:15:07 +0000http://magebase.com/?p=1670I am currently at Magento Developer’s Paradise in Ibiza. The overall theme for tomorrow’s hack-sessions will be localization. I will likely be looking at creating a starting pack for New Zealand. I am keen to hear what you think should be part of this pack. The underlying idea is to create an extension that will […]

The overall theme for tomorrow’s hack-sessions will be localization. I will likely be looking at creating a starting pack for New Zealand. I am keen to hear what you think should be part of this pack. The underlying idea is to create an extension that will contain all instructions to start using Magento in New Zealand.

The role model for the localization pack is what the German community has come up with in the German Setup extension. For example it will set tax rates for you, add additional regions, adjust email templates and also automatically create required by law CMS pages.

What do you think should be part of the New Zealand version? Keep in mind this should ideally be applicable to all stores operating in NZ.