Magento 2 How to include custom library in controller
-
03-03-2021 - |
Question
I have created custom extension with some library classes. I have placed the libraries in lib/internal/SSOSdk folder. I need to include one of the library class in my controller. I have used the below code but it gives Class not found error.
Here is my code
namespace Company\Sso\Controller\Login;
require_once('lib/internal/SSOSdk/SSO.php');
class Login extends \Magento\Framework\App\Action\Action
{
private $resultPageFactory;
private $scopeConfig;
public $storeManager;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
$this->scopeConfig = $scopeConfig;
$this->storeManager = $storeManager;
parent::__construct($context);
}
public function execute()
{
$apiUrl = 'test.com';
$clientId = '123';
$clientSecret = '456';
$params = $_GET;
$sso = new SSO($apiUrl, $clientId, $clientSecret);
try {
if($params['error']){
$sso->notifyJs(false, $params);
}else{
$sso->notifyJs(true, $params);
}
} catch (Exception $e) {
$sso->notifyJs(false, $e);
}
}
}
SSO.php
class SSO {
private $_clientId, $_clientSecret, $_hostUrl;
public function __construct($hostUrl, $clientId, $clientSecret){
$this->_hostUrl = $hostUrl;
$this->_clientId = $clientId;
$this->_clientSecret =$clientSecret;
}
public function setHostUrl($hostUrl){
$this->_hostUrl = $hostUrl;
}
.......
}
How can I do this?
Solution
try this
require_once(__DIR__ . '../../../../lib/internal/SSOSdk/SSO.php');
instead of
require_once('lib/internal/SSOSdk/SSO.php');
Also.use
new \SSO
instead of
new SSO
But I suggest converting your classes to psr-2
format php-fig.org/psr/psr-2 right solution.
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange