PHP CodeIgniter and Doctrine - codeigniter

I would like to ask if any one of you can help me.
History:
Set-Up CodeIgniter
Copy the Library of Doctrine
Create the Doctrine.php
Test the Controller - hello world - ok
Test the Model by saving data into Database - failed
Error :
A PHP Error was encountered
Severity : Warning
Message :
require(C:/CI/system/application/libraries/Doctrine/Common/ClassLoader.php\Doctrine\ORM\Configuration.php): failed to open stream: No such file or directory
Filename : Common/ClassLoader.php
Line Number : 164
Fatal error : require(): Failed opening required 'C:/CI/system/application/libraries/Doctrine/Common/ClassLoader.php\Doctrine\ORM\Configuration.php' (include_path='.;C:\php\pear') in C:\CI\system\application\libraries\Doctrine\Common\ClassLoader.php on line 164
Copy of Doctrine.Php
<?php
use Doctrine\Common\ClassLoader,
Doctrine\ORM\Configuration,
Doctrine\ORM\EntityManager,
Doctrine\Common\Cache\ArrayCache,
Doctrine\DBAL\Logging\EchoSQLLogger;
class Doctrine {
public $em = null;
public function __construct()
{
// load database configuration from CodeIgniter
require_once APPPATH.'config/database.php';
// Set up class loading. You could use different autoloaders, provided by your favorite framework,
// if you want to.
require_once APPPATH.'libraries/Doctrine/Common/ClassLoader.php';
// require_once APPPATH.'libraries/Doctrine/Common/ClassLoader.php';
$doctrineClassLoader = new ClassLoader('Doctrine', APPPATH.'libraries/Doctrine/Common/ClassLoader.php');
$doctrineClassLoader->register();
$entitiesClassLoader = new ClassLoader('models', rtrim(APPPATH, "/" ));
$entitiesClassLoader->register();
$proxiesClassLoader = new ClassLoader('Proxies', APPPATH.'models/proxies');
$proxiesClassLoader->register();
// Set up caches
$config = new Configuration;
$cache = new ArrayCache;
$config->setMetadataCacheImpl($cache);
$driverImpl = $config->newDefaultAnnotationDriver(array(APPPATH.'models'));
$config->setMetadataDriverImpl($driverImpl);
$config->setQueryCacheImpl($cache);
$config->setQueryCacheImpl($cache);
// Proxy configuration
$config->setProxyDir(APPPATH.'/models/proxies');
$config->setProxyNamespace('Proxies');
// Set up logger
$logger = new EchoSQLLogger;
$config->setSQLLogger($logger);
$config->setAutoGenerateProxyClasses( TRUE );
// Database connection information
$connectionOptions = array(
'driver' => 'pdo_mysql',
'user' => $db['default']['root'],
'password' => $db['default']['root'],
'host' => $db['default']['localhost'],
'dbname' => $db['default']['ci_database']
);
// Create EntityManager
$this->em = EntityManager::create($connectionOptions, $config);
}
}
-------------------------------------------------------------------------------------------

May be you miss the load Doctrine files into your system/application/plugin
Refer this

you should copy Doctrine folder containing DBAL, Common and ORM inside application/third-party directory.

Related

I'm trying to use guzzlehttp/guzzle in Magento 2.2.9 but it's not working

It's throwing me an error
PHP Error: Cannot instantiate interface GuzzleHttp\\ClientInterface in vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php on line 111, referer: http://127.0.0.1/local_m2/admin/admin/system_config/edit/section/active_campaign/key/6a9ce672c9414c57acd889eb50fb82020e13e651b74cf3a81b9cd8b30da45306/ here
I have already run all Magento required commands Like Setup: upgrade, di:compile and deploy but still it's throwing me this error.
I have already checked GuzzleHttp in the vendor folder, it's already installed in Magento 2.2.9
I have tried the composer require guzzlehttp/guzzle:^6.0 to reinstall the library but having no luck.
import this library:
use GuzzleHttp\Client;
use GuzzleHttp\ClientFactory;
use GuzzleHttp\Exception\RequestException;
on __construct use:
$this->client = new Client([
"base_uri" => url_base,
"timeout" => 2,
]);
and then call:
$response = $this->client->get(
url_base . "/" . url_api_point,
['headers' =>
[
'Authorization' => "Bearer {$this->token}" /* if have */
]
]
);
return json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
try this way to create an instance of GuzzleClient, im currently using a similar in a magento 2.4.4 and works fine, you donĀ“t have to inyect that on __construct()
/**
* #return \GuzzleHttp\Client
*/
public function getClient()
{
$client = new \GuzzleHttp\Client(["base_uri" => "your url", "verify" => false]);
return $client;
}

How to make wrapper for spatie/laravel-permission Contracts/Permission?

In Laravel 8 app using spatie/laravel-permission ^3.18 I
defined in bootstrap/app.php
if ( ! defined("PERMISSION_USE_SERVICES")) {
define("PERMISSION_USE_SERVICES", 'Use services');
}
and in init seeder :
$CustomerRole = Role::create(['name' => ROLE_CUSTOMER, 'guard_name' => 'web']);
$customerUseServicesPermission = Permission::create(['name' => PERMISSION_USE_SERVICES, 'guard_name' => 'web']);
$CustomerRole->givePermissionTo($customerUseServicesPermission); // means : customer use services
and when I register new user in app/Actions/Fortify/CreateNewUser.php I want to give new user
customerUseServicesPermission.
In vendor/spatie/laravel-permission/src/Contracts/Permission.php I found method :
interface Permission
{
public static function findByName(string $name, $guardName): self;
But using it I got error :
Cannot call abstract method Spatie\Permission\Contracts\Permission::findByName()
have I to make wrapper file for Contracts/Permission.php and in which way ?
Thanks!

Laravel storage path in production server

I do have a trouble to save generated excel file in the production server, I did set the storage path in /public/reports directory as like below:
$filename = "report-".date('YmdHis').".xlsx";
$storage_path = public_path('reports');
However, the file wouldn't be saved in reports folder but at the public folder, I've been tried
$storage_path = public_path().'\reports\\';
but this will save outside of the public folder.
I'm new in laravel, I appreciate if anyone can point out what is the workaround.
Edit
Here is the whole block:
public function handle()
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getStyle('C')->getAlignment()->setHorizontal('left');
$sheet->getColumnDimension('A')->setWidth(8);
$sheet->getColumnDimension('B')->setWidth(30);
$sheet->setCellValue('A1', 'title');
$sheet->setCellValue('B1', 'brief');
$reports = Report::get();
if(count($reports) > 0) {
$rowCount = 2;
foreach($reports as $report) {
$sheet->setCellValue('A' . $rowCount, $report->title);
$sheet->setCellValue('B' . $rowCount, $report->brief);
$rowCount++;
}
}
$spreadsheet->getActiveSheet()->setTitle('Report Title');
$spreadsheet->setActiveSheetIndex(0);
$export_filename = "report-".date('YmdHis').".xlsx";
\Illuminate\Support\Facades\Storage::disk('reports')->put($export_filename, $content);
$writer = new Xlsx($spreadsheet);
$writer->save($storage_path.$export_filename);
Mail::to(env('RPT_RECEIVER'))->send(new ReportsMail($storage_path.$export_filename, 'Report Name', date('F')));
exit;
}
The right way to do it in Laravel is save it in the storage directory.
Seems that you're using the PHPSpreadsheet library.
I suggest use this code to save the excel file:
$export_filename = "report-".date('YmdHis').".xlsx";
$writer = new Xlsx($spreadsheet);
$writer->save(storage_path("app/public/{$export_filename}));
Mail::to(env('RPT_RECEIVER'))->send(new ReportsMail($storage_path.$export_filename, 'Report Name', date('F')));
exit;
The code above wiill save the excel file inside storage/app/public
Then in order for the file to be accessible in public, run the command: php artisan storage:link. This will create a symlink (or shortcut) storage inside your public directory.
In order to access the file use this code:
$file_url = asset('storage/sample.xlsx');
REMEMBER, to run also the php artisan storage:link to the production server.
In congif/filesystem.php file add this after "local" => [],
'reports' => [
'driver' => 'local',
'root' => public_path().'/reports'
],
then use this code
$filename = "report-".date('YmdHis').".xlsx";
\Illuminate\Support\Facades\Storage::disk('reports')->put($filename, $content);

Class 'JTable' not found

I am using Joomla 2.5.11 . I have a php file stored in the /public_html/joomtest/components/com_jumi/files which is pasted below.
I have a PHP form which is stored in the same location i.e /public_html/joomtest/components/com_jumi/files.
I want the PHP form to call the PHP script so that an article is created in Joomla. But whenever the PHP script is called, I receive the below error
Fatal error: Class 'JTable' not found
and the line on which Joomla throws error is
$table = JTable::getInstance('Content', 'JTable', array());
PHP script
<?php
$table = JTable::getInstance('Content', 'JTable', array());
$data = array(
'catid' => 8,
'title' => 'SOME TITLE',
'introtext' => 'SOME TEXT',
'fulltext' => 'SOME TEXT',
'state' => 0,
);
if (!$table->bind($data))
{
$this->setError($table->getError());
return false;
}
if (!$table->check())
{
$this->setError($table->getError());
return false;
}
if (!$table->store())
{
$this->setError($table->getError());
return false;
}
?>
</body>
</html>
I tried putting in
require_once('/libraries/joomla/database/table.php');
but this again didnt work. Please help.
You need to define path of table file you want to use. Use the following code for include the specific table. For example:
JTable::addIncludePath(JPATH_SITE.DS.'components'.DS.'com_content'.DS.'tables');
And then call your table like below:
$con_table = JTable::getInstance('Content', 'JTable', array());
Hope this will work. Good Luck.

How to check all database for availability in CI 2

I have config file database.php with 5 databases.
How can I get 500 error with message "Site is not available" in all pages, if one of a database is not available?
I found it very interesting your question and have been doing some research to solve your problem.
I tell you my solution: the first is to activate the hooks, so in your config.php file make this change:
$config['enable_hooks'] = TRUE;
Once activated the hooks, you need to create a new hook, for it in the file config/hooks.php put something like the following:
$hook['post_controller_constructor'] = array(
'class' => 'DBTest',
'function' => 'index',
'filename' => 'dbtest.php',
'filepath' => 'hooks',
'params' => array(),
);
Thus, your hook kicks in once the controller has been instantiated, but has run no method yet. This is neccesary to use $CI = &get_instance()
To finish create the file /application/hooks/dbtest.php with content similar to the following:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class DBTest {
function index() {
$CI = &get_instance();
$databases = array(
'mysqli://user1:pass1#host1/db1',
'mysqli://user2:pass2#host2/db2',
'mysqli://user3:pass3#host3/db3',
'mysqli://user4:pass4#host4/db4',
'mysqli://user5:pass5#host5/db5',
);
foreach ($databases as $dsn) {
$db_name = substr(strrchr($dsn, '/'), 1);
$CI->load->database($dsn);
$CI->load->dbutil();
if(!$CI->dbutil->database_exists($db_name)) {
// if connection details incorrect show error
show_error("Site is not available: can't connect to database $db_name");
}
}
}
}
You must use dsn for $CI->load->database() in this way we can handle the error instead of Code Igniter when it tries to load the database.
Hope this helps.

Resources