Programmatically create a product using Craft Commerce 2? The docs for v1 mention a method craft()-&gt;commerce_purchasables-&gt;saveElement().

This is omitted in the docs for v2. Does anyone know how I can create a product programmatically in PHP?

    $product = new Product();
        $product-&gt;title = "Test Product 1";
        $product-&gt;typeId = 2;
        $product-&gt;enabled = true;
        $product-&gt;promotable = true;

    $variant = new Variant();
            $variant-&gt;isDefault = true;

    $product-&gt;setVariants([$variant]);

    Craft::$app-&gt;getElements()-&gt;saveElement($product);


With the above code I get the following error:

Call to a member function getProductTypes() on null


I know the typeId is correct, because I can output it on a product template with {{ product.typeId }}
You probably have it figured by now, but for anyone wondering, here's a complete working example.

use craft\commerce\elements\Product;
use craft\commerce\elements\Variant;

// Create product
$product = new Product();
$product-&gt;title = 'Hello world';
$product-&gt;typeId = 2;
$product-&gt;enabled = true;

// Create variant
$variant = new Variant();
$variant-&gt;title = 'hey';
$variant-&gt;sku = 'hey';
$variant-&gt;price = 123;
$variant-&gt;stock = 5;

// Save product with variant
$product-&gt;setVariants([$variant]);
Craft::$app-&gt;elements-&gt;saveElement($product);