Integrating Mailjet API v3 wrapper as Codeigniter library - php

How can I integrate the Mailjet API PHP wrapper into my Codeigniter installation as a library?
Is it as simple as placing the contents of the repository into application/libraries/Mailjet and then creating a Mailjet.php file in application/libraries which initializes Mailjet like shown below?
require 'Mailjet/vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
Please let me know if I'm on the right track. Thanks.

Yes, you are on right track. But you don't need to create CI library. Use Mailjet repository library in controller as well. Just use composer as stated in CI docs.
If you want CodeIgniter to use a Composer auto-loader, just set $config['composer_autoload'] to TRUE or a custom path in application/config/config.php.
Step by step instruction for using github repository in CodeIgniter
Set $config['composer_autoload'] = TRUE; in APPPATH.'config/config.php' file
Put composer.json file with wanted repositories/projects in APPPATH location
Do the job with composer install command through console which will make vendor and other related files and folders inside
Use it when needed in controller or in other code as shown in example bellow
example controller Mailman.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
use \Mailjet\Resources;
class Mailman extends CI_Controller
{
private $apikey = 'apy__key__here';
private $secretkey = 'apy__secret__here';
protected $mj = NULL;
public function __construct()
{
// $this->mj variable is becoming available to controller's methods
$this->mj = new \Mailjet\Client($this->apikey, $this->apisecret);
}
public function index()
{
$response = $this->mj->get(Resources::$Contact);
/*
* Read the response
*/
if ($response->success())
var_dump($response->getData());
else
var_dump($response->getStatus());
}
}
If you explicitly want to use Mailjet (or any other) repository through CI library, check in docs how to create custom library and merge this code above with it. Personaly I use repositories this way to avoid unnecessarily loading and parsing sufficient libraries.

Related

Where should I require vendor/autoload.php in CodeIgniter?

I want to add some code that will run for every controller. Adding the code to CodeIgniter's CI_CONTROLLER class seems unconventional.
Where is the right place to include code you want to run for every controller?
Here is the code:
require_once 'vendor/autoload.php';
$bugsnag = Bugsnag\Client::make("my-secret-key-is-here");
Bugsnag\Handler::register($bugsnag);
These classes both come from a dependency installed with Composer.
I suspect I should create a helper, and include it in application/config/autoload.php. But new to CodeIgniter, so not sure of conventions.
Edit: I am using CodeIgniter 3.1.6.
If you want to execute arbitrary code at different points in CodeIgniter's life cycle, you can use the hooks feature.
Official Documentation:
https://codeigniter.com/user_guide/general/hooks.html
1. Enable hooks
Go to /application/config/config.php.
Search for enable_hooks and set it to true: $config['enable_hooks'] = TRUE;
2. Add desired code to CodeIgniter's hook file:
Go to /application/config/hooks.php.
Choose the desired lifecycle to hook into (see doc link above for a list)
Add code to the lifecycle, e.g. $hook['pre_controller'] = function(){... your code goes here ...}
For this question's example, my hooks.php looks like this:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
// This is the code I added:
$hook['pre_system'] = function(){
require_once 'vendor/autoload.php';
$bugsnag = Bugsnag\Client::make("my-client-key");
Bugsnag\Handler::register($bugsnag);
}
?>
I would just extend the Controller Class.
See "Extending Core Class":
"If all you need to do is add some functionality to an existing library - perhaps add a method or two - then it’s overkill to replace the entire library with your version. In this case it’s better to simply extend the class."
...
"Tip: Any functions in your class that are named identically to the methods in the parent class will be used instead of the native ones (this is known as “method overriding”). This allows you to substantially alter the CodeIgniter core."
class MY_Controller extends CI_Controller {
....
}
Any function you put inside would be added to the core, otherwise, if you use the same name as an existing method, it would replace just that one method.
You'd name it MY_Controller.php and put it inside application/core/, where it's picked up to override CI_Controller automatically.
If you are extending the Controller core class, then be sure to extend your new class in your application controller’s constructors.
class Welcome extends MY_Controller {
public function __construct()
{
parent::__construct();
// Your own constructor code
}
public function index()
{
$this->load->view('welcome_message');
}
}
Looks like you could also use a pre_system or pre_controller hook as described here:
https://www.codeigniter.com/user_guide/general/hooks.html
Assuming it's CodeIgnitor 3.X
Go to application/config/config.php and change:
$config['composer_autoload'] = FALSE;
to
$config['composer_autoload'] = TRUE;
just below the above line include
require_once APPPATH.'vendor/autoload.php';
Or in your controller include
require_once APPPATH.'vendor/autoload.php';
From How to use composer packages in codeigniter?
Go to application/config/config.php and set $config['composer_autoload'] = FALSE; to TRUE:
Enabling this setting will tell CodeIgniter to look for a Composer
package auto-loader script in application/vendor/autoload.php.
As a result you need not to call require_once 'vendor/autoload.php';.

PHP- How to include Codeingiter class in Wordpress

I have to adapt Codeigniter module to Wordpress. It fetches data with SOAP protocol. It needs to use Codeigniter's csrf_protection.
How to include Codeigniter MY_Controller class in Wordpress?
class Balance extends MY_Controller
{
public function __construct()
{
parent::__construct();
$this->config->set_item('csrf_protection', TRUE);
require_once('addons/libraries/nusoap/nusoap.php');
}
...
You need to copy the methods in the nusoap file and try to make like other libraries setup in codeigniter library folder and then :
$this->load->library('nusoap/nusoap')
Nusoap is the class name which is in upper case letter start with and call in controller like above.
Or else you can find / download separate controller codeingiter library file from github
check it and mark accepted if it works!.
Thanks

Undefined method with Composer library and CodeIgniter

I'm working on a project and it's getting a little too hard for me...
I explain.
I need to parse PDF files with PHP, to analyse the content of those files. To do that, I use pdfparser.org library.
I firstly tried to include this library as usually, without any result.
After having read all the Internet, since this library requires Composer to be installed (and on my web hosting I can't get Composer installed), I have applied the Composer process on my Windows PC. I got the "vendor" folder with the "autoload.php" file. Fine !!
Then, I have tried to include it properly in CodeIgniter. The solution I chose is :
Creating a file "Pdfparser.php" in application/libraries/
class Pdfparser
{
public function __construct()
{
require_once APPPATH."/third_party/pdfparser.php";
}
}
Then, I add the PdfParser "Composer" application in application/third_party/, and in the /third_party/pdfparser.php I simply put :
if (!defined('pdfparser')) {
define('pdfparser', dirname(__FILE__) . '/');
require(pdfparser . 'pdfparser/autoload.php');
}
Then, I add this library to CodeIgniter /application/config/autoload.php as :
$autoload['libraries'] = array('pagination', 'form_validation','email','upload','pdfparser');
Finally, I call it in my function in application/controllers/Admin.php :
$parser = new Pdfparser();
$pdf = $parser->parseFile(myfile.pdf);
$full_text = $pdf->getText();
(This 4. block of code is directly taken from official Documentation here : http://www.pdfparser.org/documentation, and just adapted).
But now, I break the Internet... I have this error :
PHP Fatal error: Call to undefined method PdfParser::parseFile() in /path/application/controllers/Admin.php on line 3083
After having looked CodeIgniter documentation, I try to add the Composer autoloader to the core... in application/config/autoload.php I put :
$config['composer_autoload'] = APPPATH . "/third_party/pdfparser/autoload.php";
Of course, it doest not work. And I'm lost...
Use composer properly. $config['composer_autoload'] = TRUE; and inside your application folder run composer install smalot/pdfparser . Then inside your controller it should run, if not use Use :)
use Smalot\PdfParser;
class My_controller extends CI_Controller {
}
When using composer, to include a library in your project you do something like that :
composer install smalot/pdfparser
Then, to include the newly installed library, you only need to include the "autoload.php" file provided by composer :
<?php
include 'vendor/autoload.php';
$parser = new Pdfparser();
$pdf = $parser->parseFile(myfile.pdf);
$full_text = $pdf->getText();
var_dump($full_text);
Nothing more.
Replace your code
class Pdfparser
{
public function __construct()
{
require_once APPPATH."/third_party/pdfparser.php";
}
}
with
<?php
require_once APPPATH."/third_party/pdfparser.php";
class Pdfparser
{
public function __construct()
{
}
}
Include outside of your class.
Rather than using autoloading you can load library like this...
$this->load->library('library_name');
Example:
$this->load->library('pdfparser');

Accessing and using Symfony model layer from Outside the Symfony applications

What I have is a symfony application, which contains some entities along with some repositories. A second non-symfony application should interface with the first one for interacting with some logic written in it (in this very moment just using the entities and their proper repositories).
Keep in mind that the first application could have its own autoload register etc.
I thought of an API class for external applications, which stays in the app directory. To use that the application should require a script. Here is the idea:
app/authInterface.php that the external application should require:
$loader = require __DIR__.'/autoload.php';
require_once (__DIR__.'/APIAuth.php');
return new APIAuth();
and an example of a working APIAuth I wrote (the code is kind of messy: remember this is just a try but you can get the idea):
class APIAuth
{
public function __construct()
{
//dev_local is a personal configuration I'm using.
$kernel = new AppKernel('dev_local', false);
$kernel->loadClassCache();
$kernel->boot();
$doctrine = $kernel->getContainer()->get('doctrine');
$em = $doctrine->getManager();
$users = $em->getRepository('BelkaTestBundle:User')->findUsersStartingWith('thisisatry');
}
by calling it by the shell everything works and I'm happy with it:
php app/authInterface.php
but I'm wondering if I'm doing in the best way possible in terms of:
resources am I loading just the resources I really need to run my code? Do I really need the kernel? That way everything is properly loaded - including the DB connection- but I'm not that sure if there are other ways to do it lighter
symfony logics am I interacting with symfony the right way? Are there better ways?
Symfony allows using its features from the command line. If you use a CronJob or another application, and want to call your Symfony application, you have two general options:
Generating HTTP endpoints in your Symfony application
Generating a command which executes code in your Symfony application
Both options will be discussed below.
HTTP endpoint (REST API)
Create a route in your routing configuration to route a HTTP request to a Controller/Action.
# app/config/routing.yml
test_api:
path: /test/api/v1/{api_key}
defaults: { _controller: AppBundle:Api:test }
which will call the ApiController::testAction method.
Then, implement the testAction with your code you want to excecute:
use Symfony\Component\HttpFoundation\Response;
public function testAction() {
return new Response('Successful!');
}
Command
Create a command line command which does something in your application. This can be used to execute code which can use any Symfony service you have defined in your (web)application.
It might look like:
// src/AppBundle/Command/TestCommand.php
namespace AppBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class GreetCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('myapp:section:thecommand')
->setDescription('Test command')
->addArgument(
'optionname',
InputArgument::OPTIONAL,
'Test option'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$option = $input->getArgument('optionname');
if ($option) {
$text = 'Test '.$option;
} else {
$text = 'Test!';
}
$output->writeln($text);
}
}
Look here for documentation.
Call your command using something like
bin/console myapp:section:thecommand --optionname optionvalue
(Use app/console for pre-3.0 Symfony installations.)
Use whichever option you think is best.
One word of advice. Do not try to use parts of the Symfony framework when your application is using the full Symfony framework. Most likely you will walk into trouble along the way and you're making your own life hard.
Use the beautiful tools you have at your disposal when you are already using Symfony to build your application.

require_once does not work - in Zend Framework action methods

I need to integrate Authorize.net payment gateway to my Zf2 application.
Downloaded and copied the PHP SDK in php include path. The sdk has the following files
+authoriznet
+doc
+lib
+shared
+ssl
-AuthorizeNetSIM.php (and more)
-AuthorizeNet.php
My code (Zend controller) is
require_once 'path/AuthorizeNet.php'; /*This require_once AuthorizeNetSIM.php and other files)*/
class PurchaseController extends AbstractActionController{
public purchaseAction(){
$works = new AuthorizeNetException("test"); //A class defined in AuthorizeNet.php
$notFound = new AuthorizeNetSIM;
}
}
$works -> works fine, where as $notFound throws class not found exception
If i add require_once in view file (.phtml) then all classes in sdk is available to use.
Can someone explain this behaviour? How to properly use this 3rd party library in Zf2?

Categories