If you want to create url rewrites programmatically what factory should you use?

Tried a few of them but none have the right methods (like setStoreId, save, setTargetPath and setRequestPath):

Magento\UrlRewrite\Model\UrlRewriteFactory or Magento\UrlRewrite\Model\ResourceModel\UrlRewriteFactory or Magento/UrlRewrite/Service/V1/Data/UrlRewriteFactory (missing save method)


Update: If these are the only factories available how does one save a rewrite?

For example if you use Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory there is no save method:

$urlRewriteModel = $this->urlRewriteFactory->create();
$urlRewriteModel->save(); //this fails with no save method


Thanks for the help, the final solution looks like this: https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/master/src/Model/UrlRewrite.php#L139

  • Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory <= Data abstract class for url storage, we cannot use this class to create the url rewrite. We should use Magento\UrlRewrite\Model\UrlRewriteFactory. Commented Aug 27, 2016 at 15:26

1 Answer 1


If we take a look at:


        /** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory */
         protected $urlRewriteFactory;


These classes are auto-generate factory classes, we can find them under var/generation folder:

Magento\UrlRewrite\Model\UrlRewriteFactory <= Model class
Magento\UrlRewrite\Model\ResourceModel\UrlRewriteFactory <= Resource Model
Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory <= Data abstract class for url storage

Shortly, these factory classes create the object instance of themselves.

We can read more here and here.

An example - Create the url rewrites programmatically:

We should use \Magento\UrlRewrite\Model\UrlRewriteFactory

 /** @var $rewrite \Magento\UrlRewrite\Model\UrlRewriteFactory */

  • thanks, it explains how I can find factories when I need them, but still I don't understand why there is no save method in Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory Commented Aug 27, 2016 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.