I'm trying to write some code to track dependencies. Is there a way to programatically detect if a PEAR package has been installed? I'm thinking something like:
if ($some_pear_api->isPackageInstalled('FooPack')) {
echo 'FooPack is installed!';
} else {
echo 'FooPack is not installed. :(';
}
I know you can simply detect if the class file for that package exists, but I mostly want to know if PEAR has that installed because sometimes some libraries provide other means of including their code (e.g. PHPUnit has a pear channel as well as a git repo.).
Thanks for the help!
You need to use the PEAR_Registry class to do this (which is what the PEAR script itself uses).
Read Adam Harvey's blog post "pear -> list" from 3 years ago - all the details/examples you need are there.
include 'PEAR/Registry.php';
$reg = new PEAR_Registry;
foreach ($reg->listPackages() as $package) {
print "$package\n";
}
If you need this to check for specific versions of each package, then you could base something on the following example, which I provided in a comment to that blog entry:
<?php
require 'PEAR/Registry.php';
$reg = new PEAR_Registry;
define("NAME", 0);
define("VERSION", 1);
$packages = array(
array("PEAR", "1.6.2"),
array("Date", "1.4.7"),
array("Date_Holidays", "0.17.1"),
array("Validate_IE", "0.3.1")
);
foreach ($packages as $package) {
$pkg = $reg->getPackage($package[NAME]);
$version = $pkg->getVersion();
echo "{$package[NAME]} – {$package[VERSION]} – ";
echo version_compare($version, $package[VERSION], '>=') ? 'OK': 'BAD', "\n";
}
?>
If you need to copy and paste this, then it might be best for you to use the version at https://gist.github.com/kenguest/1671361.
You can use Pear/Infos packageInstalled to answer this:
<?php
require_once 'PEAR/Info.php';
$res = PEAR_Info::packageInstalled('FooPack');
if ($res) {
print "Package FooPack is installed \n";
} else {
print "Package FooPack is not yet installed \n";
}
?>
Why not just include the package and see if the class exists?
// Supress Errors. Checking is done below.
#require_once 'PHP/UML.php';
if(!class_exists('PHP_UML'))
{
throw new Exception('PHP_UML is not installed. Please call `pear install PHP_UML` from the command line',1);
}
// Code to use PHP_UML below...
$uml = new PHP_UML();
Related
I'm playing around with Cloud Translation API v3 in PHP. I went through setup process and tried simple translation shown here and it worked. Then I wanted to test glossaries so I tried to add one as described here. When I'm trying to call the function:
protected function createGlossary()
{
$translationServiceClient = new TranslationServiceClient();
$projectId = 'my-project-id';
$glossaryId = 'my-new-glossary';
$inputUri = 'gs://bucket/file.csv';
$formattedParent = $translationServiceClient->locationName(
$projectId,
'us-central1'
);
$formattedName = $translationServiceClient->glossaryName(
$projectId,
'us-central1',
$glossaryId
);
$languageCodesElement = 'pl';
$languageCodesElement2 = 'en';
$languageCodes = [$languageCodesElement, $languageCodesElement2];
$languageCodesSet = new LanguageCodesSet();
$languageCodesSet->setLanguageCodes($languageCodes);
$gcsSource = (new GcsSource())
->setInputUri($inputUri);
$inputConfig = (new GlossaryInputConfig())
->setGcsSource($gcsSource);
$glossary = (new Glossary())
->setName($formattedName)
->setLanguageCodesSet($languageCodesSet)
->setInputConfig($inputConfig);
try {
$operationResponse = $translationServiceClient->createGlossary(
$formattedParent,
$glossary
);
$operationResponse->pollUntilComplete();
if ($operationResponse->operationSucceeded()) {
$response = $operationResponse->getResult();
printf('Created Glossary.' . PHP_EOL);
printf('Glossary name: %s' . PHP_EOL, $response->getName());
printf('Entry count: %s' . PHP_EOL, $response->getEntryCount());
printf(
'Input URI: %s' . PHP_EOL,
$response->getInputConfig()
->getGcsSource()
->getInputUri()
);
} else {
$error = $operationResponse->getError();
// handleError($error)
}
} finally {
$translationServiceClient->close();
}
}
it returns an error:
Failed to build request, as the provided path (google.longrunning.Operations/GetOperation) was not found in the configuration.
It throws error at $operationResponse->pollUntilComplete();. The file in bucket contains just one line - test,test.
Then when I try to call function that lists all glossaries, it works but it doesn't return any.
What can cause this problem and how do I add glossary?
You need to install gRPC extension for PHP.
Info: https://cloud.google.com/php/grpc
Install gRPC for PHP
gRPC is a modern, open-source, high-performance remote procedure call framework. If you want to use PHP client libraries for gRPC-enabled APIs, you must install gRPC for PHP. This tutorial explains how to install and enable gRPC.
Install the gRPC extension for PHP.
sudo pecl install grpc
Enable the gRPC extension for PHP.
Add this line anywhere in your php.ini file, for example, /etc/php7/cli/php.ini. You can find this file by running php --ini.
extension=grpc.so
so this is my code:
<?php
echo 'hey1';
set_time_limit(0);
date_default_timezone_set('UTC');
echo 'hey2';
require __DIR__.'/../vendor/autoload.php';
echo 'hey3';
/////// CONFIG ///////
$username = 'NetsGets';
$password = 'NetsGetsWebsite';
$debug = true;
$truncatedDebug = false;
//////////////////////
$ig = new \InstagramAPI\Instagram($debug, $truncatedDebug);
try {
$ig->login($username, $password);
} catch (\Exception $e) {
echo 'Something went wrong: '.$e->getMessage()."\n";
exit(0);
}
try {
$feed = $ig->discover->getExploreFeed();
// Let's begin by looking at a beautiful debug output of what's available in
// the response! This is very helpful for figuring out what a response has!
$feed->printJson();
// Now let's look at what properties are supported on the $feed object. This
// works on ANY object from our library and will show what functions and
// properties are supported, as well as how to call the functions! :-)
$feed->printPropertyDescriptions();
// The getExploreFeed() has an "items" property, which we need. As we saw
// above, we should get it via "getItems()". The property list above told us
// that it will return an array of "Item" objects. Therefore it's an ARRAY!
$items = $feed->getItems();
// Let's get the media item from the first item of the explore-items array...!
$firstItem = $items[0]->getMedia();
// We can look at that item too, if we want to... Let's do it! Note that
// when we list supported properties, it shows everything supported by an
// "Item" object. But that DOESN'T mean that every property IS available!
// That's why you should always check the JSON to be sure that data exists!
$firstItem->printJson(); // Shows its actual JSON contents (available data).
$firstItem->printPropertyDescriptions(); // List of supported properties.
// Let's look specifically at its User object!
$firstItem->getUser()->printJson();
// Okay, so the username of the person who posted the media is easy... And
// as you can see, you can even chain multiple function calls in a row here
// to get to the data. However, be aware that sometimes Instagram responses
// have NULL values, so chaining is sometimes risky. But not in this case,
// since we know that "user" and its "username" are always available! :-)
$firstItem_username = $firstItem->getUser()->getUsername();
// Now let's get the "id" of the item too!
$firstItem_mediaId = $firstItem->getId();
// Finally, let's get the highest-quality image URL for the media item!
$firstItem_imageUrl = $firstItem->getImageVersions2()->getCandidates()[0]->getUrl();
// Output some statistics. Well done! :-)
echo 'There are '.count($items)." items.\n";
echo "The first item has media id: {$firstItem_mediaId}.\n";
echo "The first item was uploaded by: {$firstItem_username}.\n";
echo "The highest quality image URL is: {$firstItem_imageUrl}.\n";
} catch (\Exception $e) {
echo 'Something went wrong: '.$e->getMessage()."\n";
}
?>
After running this code, the only things that print are hey1 and hey2. Based on my own reasearch, I concluded that autoload.php is one of the necessery files for the composer to run, but it also seems to be the problem that stops the php from running. This code is from https://github.com/mgp25/Instagram-API. Pease help!
1) If you don't have Composer, install it. For example:
sudo apt-get install composer -y
2) Run:
composer require mgp25/instagram-php
3) Type:
cd vendor
ls
The very first file you see listed should be autoload.php.
I'm developing a php module to Magento 1.9.2.4. I want to check if my module is enable or disable, but it is not working. What is wrong ?
Module folder: C:\wamp\www\magento\app\code\core\Projetos\HelloWorld
My code:
<?php
require_once 'app/Mage.php';
Mage::app();
$moduleName = 'Projetos_HelloWorld';//eg Mage_Cms
if(Mage::getConfig()->getModuleConfig($moduleName)->is('active', 'true')) {
//$product = new Projetos_HelloWorld_Model_Product;
//$product->sayHello();
echo "Module Enable";
} else {
echo "Module Disable";
}
?>
Thank you
I guess you'are not following standard magento module creating method.
If you would like to know whether particular module is enable or not then you have to check it from app/etc/modules/name_of_module.xml
Please have a look at how to create an extension in magento.
http://www.pierrefay.com/magento-developper-guide-howto-tutorial-5
I hope this will help you out.
Thanks,
Sam
Try this
<?php
if (Mage::helper('core')->isModuleEnabled('Projetos_HelloWorld'))
{
echo "Module Enable";
} else {
echo "Module disabled";
}
I want to use https://github.com/HelloFax/hellosign-php-sdk in Yii2 project so I followed following step
1 ) updated composer.json with "hellosign/hellosign-php-sdk": "3.*#dev" in require section
2) run composer update in CMD (I work with window 7)
so it downloaded required libraries (hellosign-php-sdk and libary) in vendor
3 ) include following code in controller file
$client = new HelloSign\Client('df754dd564e52fb2891a60eb2fea777b5320397********');
$response = $client->getSignatureRequest('f6197945000616b383d4752*****');
if ($response->isComplete()) {
echo 'All signers have signed this request.';
} else {
foreach ($response->getSignatures() as $signature) {
echo $signature->getStatusCode() . "\n";
}
}
Error
Unable to find 'app\controllers\HelloSign\Client' in file: C:\wamp\www\yii2hellosign/controllers/HelloSign/Client.php. Namespace missing?
How to solve this issue, any help ?
the library use psr-0 autoload, so you need to prepend classname with \ , like this:
$client = new \HelloSign\Client('...');
How do I from PHP code if a PECL extension is installed or not?
I want gracefully handle the case when an extension is not installed.
I think the normal way would be to use extension-loaded.
if (!extension_loaded('gd')) {
// If you want to try load the extension at runtime, use this code:
if (!dl('gd.so')) {
exit;
}
}
get_loaded_extensions fits the bill.
Use like this:
$ext_loaded = in_array('redis', get_loaded_extensions(), true);
Have you looked at get_extension_funcs?
Couple different ways. You can just check for the existence of the class, or even a function: class_exists, function_exists, and get_extension_funcs:
<?php
if( class_exists( '\Memcached' ) ) {
// Memcached class is installed
}
// I cant think of an example for `function_exists`, but same idea as above
if( get_extension_funcs( 'memcached' ) === false ) {
// Memcached isn't installed
}
You can also get super complicated, and use ReflectionExtension. When you construct it, it will throw a ReflectionException. If it doesnt throw an exception, you can test for other things about the extension (like the version).
<?php
try {
$extension = new \ReflectionExtension( 'memcached' );
} catch( \ReflectionException $e ) {
// Extension Not loaded
}
if( $extension->getVersion() < 2 ) {
// Extension is at least version 2
} else {
// Extension is only version 1
}