Looked around and can't really find an answer.
I have a web app that is sending SMS messages using the Twilio SDK
Some installs have Twilio installed and some do not.
I want this code to run only if the Twilio files exist.
The regular code is:
require_once ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php';
use Twilio\Rest\Client;
I have tried
if(file_exists(ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php')) {
require_once ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php';
use Twilio\Rest\Client;
}
and also
if(file_exists(ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php')) {
require_once ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php';
}
if(class_exists(Twilio\Rest\Client)) {
use Twilio\Rest\Client;
}
if(file_exists(ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php')) {
require_once ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php';
}
use Twilio\Rest\Client;
and always get
syntax error, unexpected 'use'
Is there a way to make this conditional?
Why not use use unconditionally?
<?php
use Twilio\Rest\Client;
if (is_file(ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php')) {
require_once ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php';
}
I can run this code without any issue.
Probably risking name conflicts with Twilio\Rest\Client but I think you'd have this either way.
Thank you marco-a
Ended up using
use Twilio\Rest\Client;
if (file_exists(ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php')) {
require_once ABSPATH.'php/vendor/twilio-php-master/Twilio/autoload.php';
}
Still not sure why putting the use statement before works, but it does lol
Related
I a'm trying to use the following script from Github: https://github.com/php-webdriver/php-webdriver
Installing with composer in "/mnt/hgfs/" was easy, but loading the class in a php file seems impossible
As you can see, there is a hyphen in the name, and i can't seem to load the class in any way. I have googled for a lot and tried many things, but same problem, either i get:
Trying to use the hyphen in namespace and use i get
PHP Parse error: syntax error, unexpected '-', expecting '{' in
/mnt/hgfs/test.php on line 3
Replacing hyphen with underscore, or just removing it i get:
PHP Fatal error: Uncaught Error: Class
'php_webdriver\WebDriver\Remote\DesiredCapabilities' not found in
/mnt/hgfs/test.php:10
This is how my code looks (/mnt/hgfs/test.php):
namespace php_webdriver\WebDriver;
require 'vendor/autoload.php';
use php_webdriver\WebDriver\Chrome\ChromeOptions;
use php_webdriver\WebDriver\Chrome\ChromeDriver;
use php_webdriver\WebDriver\Remote\DesiredCapabilities;
use php_webdriver\WebDriver\Remote\RemoteWebDriver;
$host = 'http://localhost:4444/wd/hub'; // this is the default
$capabilities = DesiredCapabilities::htmlUnitWithJS();
{
$options = new ChromeOptions();
$options->addArguments(array(
'--disable-extensions',
'--no-sandbox',
'--headless',
'--no-proxy-server'
));
$capabilities = DesiredCapabilities::chrome();
$capabilities->setCapability(ChromeOptions::CAPABILITY, $options);
$capabilities->setPlatform("Linux");
}
$driver_spec = RemoteWebDriver::create($host, $capabilities, 600000, 600000);
How should I load this class?
There are a couple of things wrong here:
namespace php_webdriver\WebDriver;
You shouldn't be trying to add your code to the webdriver namespace. For a test script you don't need your own namespace. You can probably delete this line.
As for:
require 'vendor/autoload.php';
use php_webdriver\WebDriver\Chrome\ChromeOptions;
use php_webdriver\WebDriver\Chrome\ChromeDriver;
use php_webdriver\WebDriver\Remote\DesiredCapabilities;
use php_webdriver\WebDriver\Remote\RemoteWebDriver;
I get the impression you're not 100% familiar with how PSR-4 / autoloading works. The namespace is mapped to a code directory by autoload.php, and the two don't necessarily have to have the same naming structure.
Take a look at the composer.json in the webdriver project, and pay attention to the PSR-4 section.
"Facebook\\WebDriver\\": "lib/" tells you that anything in the lib directory is to be considered as being in the Facebook\WebDriver namespace.
Try
require 'vendor/autoload.php';
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Chrome\ChromeDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
If I fail to include a file in PHP, it reports.
But how do I know I successfully import GuzzleHttp\Cookie\CookieJar Class ?
And how do I know it is a valid Class ?
namespace GuzzleHttp;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Promise;
It is important to note that the use statement will NOT include that class, therefore it would be impossible to detect if this (statement) was succesful.
However if you would try to instantiate one of the imported classes and the import would have failed, you'd get an error.
You usually use an autoloader for this, such as composer, but you can also write one yourself. More information about this at this page: What is Autoloading; How do you use spl_autoload, __autoload and spl_autoload_register?
Nowadays most application use autoload feature from composer.
You can check if a class exist via code:
if (!class_exists(CookieJar::class)) {
throw new Exception('class not found');
}
but class_exists probably more useful when you do dynamic stuff.
Follow the instruction to use composer to install dukpt-php, write a simple code:
<?php
use DUKPT\DerivedKey;
use DUKPT\KeySerialNumber;
use DUKPT\Utility;
$ksnObj = new KeySerialNumber($ksn);
$decryptionKey = DerivedKey::calculateDataEncryptionRequestKey($ksnObj, $bdk);
But get error:
Class 'DUKPT\KeySerialNumber' not found
You need to include composer's autoloader:
require __DIR__ . '/vendor/autoload.php';
You can read the documentation here.
I've seen some inconsistencies (really!?!) in PHP with this type of statement where you may need to use a rooted namespace 'use' statement:
use \DUKPT\Utility.
I'm trying to use a php library called tcpdf-extension. This library uses namespaces and 'use' commmands. The rest of my code does not. I'm pretty new to namespaces and do not understand how to use them.
If I include the library, I get problems with php not being able to find other included/required files. For instance: 'PHP Fatal error: require_once(): Failed opening required <filepath>(include_path='.;C:\php\pear') in <filepath> on line 29'
Another issue is some of my previously working website pages just hang without any error message. If I remove the include for the library, everything goes back to normal.
If I use the library in a separate page from the rest of my code, then there's no problems, but as soon as I include it in any other page, it fails.
Why is this happening and what can I do to fix it?
Update: example of including the library:
require_once ('tcpdf/Extension/Helper.php');
require_once ('tcpdf/Extension/Table/Table.php');
require_once ('tcpdf/Extension/Table/Cell.php');
require_once ('tcpdf/Extension/Table/Row.php');
require_once ('tcpdf/Extension/Table/TableConverter.php');
require_once ('tcpdf\Extension\Attribute\AbstractAttribute.php');
require_once ('tcpdf\Extension\Attribute\BackgroundAttribute.php');
require_once ('tcpdf\Extension\Attribute\BackgroundFormatterOptions.php');
if this is commented out, the problems go away, but I need to use this library.
Here's a section from Table.php:
<?php
namespace Tcpdf\Extension\Table;
class Table{
...
Here's a section from Cell.php:
namespace Tcpdf\Extension\Table;
use Tcpdf\Extension\Attribute\BackgroundAttribute;
class Cell
{
...
My guess is that the use and/or namespace commands have something to do with it because that's the only thing about this library that is different than other libraries I've used without any problems. I've also tried commenting out the use commands and that makes code outside the library work okay, but it makes the library not work. Perhaps after I include this library I need to give another 'use' command to get back to the right namespace for the rest of my code. However, since I've never set a namespace for the code, I don't know what the use command would be.
This is the library in question:
https://github.com/naitsirch/tcpdf-extension
Another detail that might be relevant: Most of my code is procedural style. I often make use of classes, but most of this (very large) code base is not in a class at all. If it were all in classes, I'm sure I could add use statements for each class, but that is not the case.
You should use "use" operator in your file by below way.
use Tcpdf\Extension\Table\Table as TableClass;
after this, "new TableClass();" would instantiate a Tcpdf\Extension\Table\Table Class
For more info, check below link:-
PHP namespaces and "use"
Hope it will help you :-)
The only way I have found to use this library with my existing, non-namespaced, procedural code is to remove all use statements and namespace statements from the library. This library only has 8 files, so this wasn't hard. I'd still like to hear answers from people if they have a better approach, as I'm sure this issue will come up again.
As far as I understand, I cannot simply use use Twilio to make it work. Thus, I tried require_once and require. The path should also be correct
I tried using require_once
$twilioDir = '../vendor/twilio/sdk/Services/Twilio.php';
require_once($twilioDir);
$client = new Services_Twilio($_ENV['TWILIO_ACCOUNT_SID'], $_ENV['TWILIO_AUTH_TOKEN']);
Class 'App\Http\Controllers\Services_Twilio' not found
What am I doing wrong?
Also, using require gave me error:
Cannot redeclare Services_Twilio_autoload() (previously declared in /var/www/Laravel/vendor/twilio/sdk/Services/Twilio.php:9)
I tried adding false to the line spl_autoload_register('Services_Twilio_autoload', false); in Twilio.php, but no luck
As far as I understand, I cannot simply use use Twilio to make it work.
Correct, because the class is named Services_Twilio.
use Services_Twilio; should do the trick.
Laravel handles autoloading for you. You shouldn't need to manually require the library unless Twilio has goofed something in their Composer setup.
I don't know who told you that you can't use Twilio but you can certainly use Twilio.
Grab the composer package - composer require aloha/twilio
Register the ServiceProvider in app.php like any other vendor: 'Aloha\Twilio\Support\Laravel\ServiceProvider', should be added to the providers array.
Register the facade to make life easy - in app.php add to the aliases array: 'Twilio' => 'Aloha\Twilio\Support\Laravel\Facade',
(optional) run php artisan vendor:publish so you can manage the assets that the vendor exposes to you.
Because we previously added the facade to the aliases array in our app.php we can correctly use Twilio; within our classes.
If you didn't do 3, then you need to reference the full namespace path; use Aloha\Twilio\Support\Laravel\Facade which will give you access to Twilio:: inside of that particular file.
Edit
I should note that you do not use Twilio from within the class, you must reference it outside of the class and before the class.
use Twilio; //Aloha\Twilio\Support\Laravel\Facade
class MyController {
/**
* Now you can use Twilio::whatever
*/
}
You have to import it at the top of the file.
I am not sure about the full path to the file but I am guessing it should be something like:
use Twilio\SDK\Services\Twilio
Update:
Follow the guide here:
https://github.com/aloha/laravel-twilio
The accepted answer didn't work for me.
Background: My code had worked for a while with use Services_Twilio;, but then I stopped using Twilio for months (or maybe more than a year), and then I was getting this error.
What ended up working was updating my code to say use Twilio\Rest\Client; instead and then create the client object via new Client($this->config['account_sid'], $this->config['auth_token']);.
This seems to be Twilio's newer way of doing things.
These docs helped.