CodeIgniter - Why does library load fine in view but not in controller - php

I'm using Stripe's php library. DL link: https://code.stripe.com/stripe-php-latest.zip
I've included the library like so inside of a view:
require_once(APPPATH.'libraries/stripe/lib/stripe.php');
Everything works fine when I do this in a view, but if I attempt to do it in a controller I get a server error. Why?
I have tried codeigniters load library method, but still a server error. I've change all capitals to lowercases, still the error.

Loading Packages:
$this->load->add_package_path(APPPATH.'third_party/stripe/');
$this->load->library('stripe');
Documentation: Application "Packages" section
http://ellislab.com/codeigniter/user-guide/libraries/loader.html

If you use third_party libraries, like for example the Facebook PHP SDK, use the following code:
$this->_obj->load->add_package_path(APPPATH.'third_party/facebook/');
$this->_obj->load->library('facebook', $config);
$this->_obj->load->remove_package_path(APPPATH.'third_party/facebook/');
And place the files for this library in the /third_party/facebook/libraries/ folder.
Note: It's a common mistake to place the files directly in '/facebook/' instead of in '/libraries/' (and also not mentioned in the documentation, too bad).

You can use the stripe native library by adding as codeigniter helper.
step 1: put the stripe package into helper directory
step 2: rename the init.php to init_helper.php
step 3: load the helper into your controller
$this->load->helper('stripe/init');
step 4: call stripe library
try
{
// set api key
\Stripe\Stripe::setApiKey('YOUR_SECRET_STRIPE_API_KEY');
// create customer
$customer_detail = \Stripe\customer::create(array(
'email' => 'customer_email#testdomain.com'
));
echo $customer_detail->id;
}
catch (Exception $e)
{
$error = $e->getMessage();
echo $error;
}

Try putting your library on application/libraries and then load your librarie with
$this->load->libraries('Stripe.php');

Related

How can i send Mails within my Typo3 extension

I get results from a jQuery Survey in JSON within my Typo3 Extension. Now I want to send these results with the Typo3 Mail API to my Inbox. According to the documentations following shoud do the work
$mail = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
$mail->from(new \Symfony\Component\Mime\Address('john.doe#example.org', 'John Doe'));
$mail->to(
new \Symfony\Component\Mime\Address('receiver#example.com', 'Max Mustermann'),
new \Symfony\Component\Mime\Address('other#example.net')
);
$mail->subject('Your subject');
$mail->text('Here is the message itself');
$mail->html('<p>Here is the message itself</p>');
$mail->attachFromPath('/path/to/my-document.pdf');
$mail->send();
so my code looks like this:
namespace TYPO3\CMS\Core\Mail;
if (!file_exists( dirname(__DIR__, 2).'/vendor/autoload.php' )) {
throw new \RuntimeException(
'Could not find vendor/autoload.php, make sure you ran composer.'
);
} else {
require dirname(__DIR__, 2).'/vendor/autoload.php';
}
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MailUtility;
$mail = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
$mail->from(new \Symfony\Component\Mime\Address('john.doe#example.org', 'John Doe'));
$mail->to(
new \Symfony\Component\Mime\Address('receiver#example.com', 'Max Mustermann'),
new \Symfony\Component\Mime\Address('other#example.net')
);
$mail->subject('Your subject');
$mail->text('Here is the message itself');
$mail->html('<p>Here is the message itself</p>');
$mail->attachFromPath('/path/to/my-document.pdf');
$mail->send();
I just getting errors. Does anyone know how i can achieve this?
Following error i get
Notice: Undefined index: TYPO3_CONF_VARS in /var/www/html/local_packages/ext_sitepackage/public/typo3/sysext/core/Classes/Mail/Mailer.php on line 170
Apparently this is the same question as you already posted here.
This will never work like this. You need to either build a fully fledged TYPO3 extension or a standalone application using symfony/mailer directly.
Your script is missing $GLOBALS['TYPO3_CONF_VARS']['MAIL'].
You stumble over the fact that you're programming past the conventions and requirements of TYPO3, but then you're surprised that the framework's functions don't work...
Create a middleware in your sitepackage, and register it correctly. Check for a special route and let the rest run. If handling, use the code there.
You need to run the mailing code in a (full) bootstrapped Typo3 context:
in a middleware
extbase plugin registered with pageNum directly
Your pasted code looks weired in a lot of ways. Just putting a file in a extension folder do not mean that is correctly a typo3 extension.
Maybe you want to start and have a proper extension setup first, with the corresponding readings:
ext_emconf.php / composer.json as a minimum
code files in 'Classes/' subfolders
then decide with which way you want to handle the "ajax" call and send the email, there are several possibilities (as already mentioned above) .. than read and implement that solution the proper and correct way.
Just having a php file directly referenced/called and just bootstpping the composer autoloader do not and never will be bootstrapping Typo3 with all needed configuration bootstrapping (gathering confings from extensions, Local/AdditionalConfiguration, siteconfig and and and).
And generally a package/extension should have a namespace something like following (as a convention):
<extensionname.....
an thus registered as psr-4 autoloading in your extension composer.json ..
Starting to implement the peaces to simulate a Typo3 bootstpraping in that file is not good and will make a lot of headache ... it's easier to have a proper sitepacke/extension structure.

Yii2: How to force using fallback MessageFormatter method?

My website is with a hosting provider that has the MessageFormatter class available on the server (Linux, PHP 7.0.27) but it is an old ICU version (4.2.1) that doesn't support my message {number,plural,=0{# available} =1{# available} other{# available}} and gives the error:
Message pattern is invalid: Constructor failed
msgfmt_create: message formatter creation failed: U_ILLEGAL_CHARACTER
...because of the =1 and =2 notation.
I'm not able to make changes to the server so how can I force using the fallback method provided by Yii2 which works just fine?
There is this hacky way you can try.
Copy the yii\i18n\MessageFormatter code to a new file. Name it MessageFormatter.php and place somewhere in your application (but not in vendor folder).
In this new file change the format() method to:
public function format($pattern, $params, $language)
{
$this->_errorCode = 0;
$this->_errorMessage = '';
if ($params === []) {
return $pattern;
}
return $this->fallbackFormat($pattern, $params, $language);
}
Don't change anything else (including namespace).
Now let's use Yii mapping.
Find a place in your application when you can put code that will be run every time in bootstrapping phase. Good place for this is common/config/bootstrap.php if you are using "Advanced Template"-like project.
Add there this line:
Yii::$classMap['yii\i18n\MessageFormatter'] = 'path/to/your/MessageFormatter.php';
Obviously change the path to the one you've chosen. Now Yii autoloader will load this class from your file instead of the original Yii vendor folder (as mentioned in Class Autoloading section of the Guide).
In the modified file MessageFormatter method presence of intl library is never checked so fallback is used as default.
The downside of this trick is that you need to update manually your file every time original Yii file is changed (so almost every time you upgrade Yii version).
Another approach is to configure I18N component in your application to use your custom MessageFormatter where you can extend the original file and just override format() method inside without modifying class map.

The blade template engine can be used with codeigniter?

The template engine called blade can be used with codeigniter or pure php? I know that it can be used with laravel and I'd like to know if also can be used with any other php framework or with pure php
Blade can be used stand-alone in PHP.
This means you can comfortably use it in CodeIgniter.
https://github.com/PhiloNL/Laravel-Blade
Then again, you will need composer for that.
Alternatively you could use this CodeIgniter Library to simulate Blade: CodeIgniter Slice-Libray
It works pretty like Blade and it was designed directly for CodeIgniter!
For the record and as answer to another post:
I tested many libraries to run blade outside Laravel (that i don't use) and most (with all respect of the coders) are poor hacks of the original library that simply copied and pasted the code and removed some dependencies yet it retains a lot of dependencies of Laravel.
I created an alternative for blade that its free (MIT license, i.e. close source/private code is OK) in a single file and without a single dependency of an external library. You could download the class and start using it, or you could install via composes (composer require eftec/bladeone). So even composer is optional.
https://github.com/EFTEC/BladeOne
https://packagist.org/packages/eftec/bladeone
Its 100% compatible sans the Laravel's own features (extensions).
You can use BladeView library for CI.
NB: I ported this library
class Welcome extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library("bladeview");
}
public function renderView(){
$data=array(
"name"=>"Jhon",
"age"=>21
);
$this->bladeview->render("test", $data);
}
public function renderString(){
$data=array(
"name"=>"Jhon",
"age"=>21
);
$string="Hello I'm \{{$name}}. My age is \{{$age}}";
$this->bladeview->render($string, $data,false);
}
}
then in view.blade.php you can render like you do in laravel blade.
Hello my name is {{$name}}. My Age is {{$age}}.
Output:
Hello my name is Jhon. My Age is 21.
I have done a full write up here: http://mstd.eu/index.php/2017/03/02/using-the-laravel-blade-templating-engine-in-codeigniter-3/
Basically, include the package with composer (you need to set CI up to use composer), then create a blade instance passing it your view and cache folder like so:
$blade = new BladeInstance(__DIR__ . "/../views", __DIR__ . "/../cache/views");
echo $blade->render("index");

Using angelleye paypal with simplemvc framework

I have used composer to download the Angell EYE PayPal library into my vendor directory. Now I'm trying to call the class within a controller.
I've tried various methods:
Use \angelleye\PayPal;
at the top of page. I've tried using the require() method.
Within the controller I have used
$paypal = PayPal::PayPal($payment);
And a few other ways, but I just get the error Class not found at line 179 and I'm not sure why.
You just need to load a config file (depending on your framework) and the autoloader.
require_once('includes/config.php');
require_once('vendor/angelleye/paypal-php-library/autoload.php');
Of course, adjust the paths to suit where you have those saved, but the autoloader is what makes the classes available to you.
If you want more direct help you can submit a ticket here.
Thanks for response.
I actually managed to get it working on the framework.
I did nt have to load anything or require the class as the composer autoload must do it for me in the framework.
I simply added :
$PayPal = new \angelleye\PayPal\PayPal($PayPalConfig);
and it started to work.
Im guessing if i want to use the PayFlow i would call using:
$PayPal = new \angelleye\PayPal\PayFlow($PayPalConfig);
I will definately post back if the rest of the proccess fails to work.

CAS Authentication with Yii Framework

I'm facing some troubles trying to implement CAS Authentication with Yii framework. I downloaded the client classes and everything is working when I'm not using any framework, but when I try to integrate with Yii validation seems to not be working at all.
Can Anyone please describe the process to successfuly make a CAS validation with yii.
I put the clients files under /myapp/protected/vendor directory, then I put the following lines at the begining of the controller
Yii::import('application.vendors.*');
require_once('CAS/CAS.php');
Then I created the method for use my CAS Classes
public function casValidation()
{
phpCAS::client(CAS_VERSION_2_0, $server, $port, "/cas",false);
phpCAS::setNoCasServerValidation();
phpCAS::forceAuthentication();
if(isset($_REQUEST['logout']))
{
phpCAS::logout();
}
}
And Finally I try to validate from my index action
public function actionIndex()
{
$this->casValidation();
$this->render('index');
}
But in the web browser shows the following error
PHP warning
include(CAS_Client.php) [function.include]: failed to open >stream: No such file or directory
C:\app\vertrigo\Vertrigophp52\www\testyii\framework\YiiBase.php(427)
Am I Missing something? What should I do to make things work?
Finally I got it working, turns out that I had made a couple of mistakes.
First of all I should not have been using require statement. The reason for this is that Yii alredy take care of loading the classes via the import method as shown below.
Yii::import('application.vendor.CAS.*')
Second thing I had a typo on this import, I had
/* This is wrong */
Yii::import('application.vendors.CAS.*')
instead of
/* This is correct */
Yii::import('application.vendor.CAS.*')
So Yii was looking for the vendors directory which does not exist.
And finally, to successfully use the import method the file containing your class has to have the same name. So if you have a class name user you have to name your file user.php in order to Yii can load it successfully.

Categories