In the previous article, we looked at how to enable or disable Manager plugins based on TV values. In this article and the following one, we'll look at how to get the path of a MODX Media Source.
At some point, you may want to get the path of a MODX File Media Source in code for a snippet that, for example, does something with the files of the Media Source. This is relatively simple because there are built-in methods in the
modFileMediaSource object to do just that. Note that these methods are only appropriate for Media Sources that are streams (e.g., a file system).
Here is some code for a simple snippet that will get and display the type, class_key, base path, and base URL of a Media Source.
/** @var $ms 'modMediaSource' */ $mediaSourceId = 12; $output = ''; $ms = $modx->getObject('modMediaSource', $mediaSourceId); $ms->initialize(); $type = $ms->getTypeName(); $classKey = $ms->get('class_key'); $basePath = $ms->getBasePath(); $baseURL = $ms->getBaseUrl(); $output .= "<br>Type: " . $type; $output .= "<br>Class Key: " . $classKey; $output .= "<br> Base Path: " . $basePath; $output .= "<br> Base URL: " . $baseURL; return $output;
Notice that line near the top of the code that calls
$ms->initialize(). This is critical, since the methods called use the MODX
fileHandler service, which won't be available unless we call the Media Source's
initialize() method first.
You have to specify the ID of the Media Source in the code. You can find the ID by going to Media -> Media Sources on the Manager's Top Menu. Getting the Media Source object by ID will be slightly faster, but if you prefer to get the Media Source by name, you can do this:
$ms = $modx->getObject('modMediaSource', array('name' => 'Filesystem'));
Replace 'Filesystem' with the name of the Media Source if you want a different Media Source. Be sure the name is correct or the Media Source won't be found.
You will get the full (absolute) path to the Media Source and a full URL even if you have the Media Source set to use a relative base path and URL. The URL will *not* include the protocol or server name. If you want a full URL, you can add this to the code above this:
$siteUrl = $modx->getOption('site_url'); $fullUrl = $siteUrl . $baseUrl;
Relative Path and URL
What if you want a relative path or URL? We'll see how to get that in the next article.
In the next article, we'll look at how to get the relative path and URL for a Media Source.
Looking for high-quality, MODX-friendly hosting? As of May 2016, Bob's Guides is hosted at A2 hosting. (More information in the box below.)