Replies: 5 comments 10 replies
-
You don't need |
Beta Was this translation helpful? Give feedback.
3 replies
-
DbHandler <?php
use Cycle\Annotated;
use Cycle\Annotated\Locator\TokenizerEmbeddingLocator;
use Cycle\Annotated\Locator\TokenizerEntityLocator;
use Cycle\Database\Config;
use Cycle\Database\DatabaseInterface;
use Cycle\Database\DatabaseManager;
use Cycle\ORM;
use Cycle\ORM\Entity\Behavior\EventDrivenCommandGenerator;
use Cycle\Schema;
use Cycle\Schema\Compiler;
use Cycle\Schema\Registry;
use Spiral\Tokenizer\ClassLocator;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\Finder\Finder;
/**
* Класс для работы с базой данных.
*
* @since 171.3.0
*/
abstract class DbHandler {
/**
* Подключение к базе данных
*
* @var DatabaseManager|null
*/
private static ?DatabaseManager $connection = null;
/**
* Объект подключения и управления баз данных.
* Необходимо само подключение к базе данных, чтобы получить ORM
*
* @var ORM\ORM|null
*/
private static ?ORM\ORM $manager = null;
/**
* @param bool $user_db
*
* @return DatabaseInterface
*/
public static function getDb(bool $user_db = false) : DatabaseInterface {
self::init();
$db = $user_db ? 'user' : 'default';
return self::$connection->database($db);
}
/**
* Инициирует подключение к базе данных
*
* @since 171.3.0
* @return void
*/
private static function init() : void {
global $config;
if (is_null(self::$connection)) {
include_once(DLEPlugins::Check(ENGINE_DIR . '/data/dbconfig.php'));
$db_name_port = explode(':', DBHOST);
$port = count($db_name_port) > 1 ? (int) $db_name_port[1] : 3306;
$host = $db_name_port[0];
$dbConfig = new Config\DatabaseConfig([
'databases' => [
'default' => [
'driver' => 'mysql',
'prefix' => PREFIX . '_'
],
'user' => [
'driver' => 'mysql',
'prefix' => USERPREFIX . '_'
]
],
'connections' => [
'mysql' => new Config\MySQLDriverConfig(
connection : new Config\MySQL\TcpConnectionConfig(
database : DBNAME,
host : $host,
port : $port,
user : DBUSER,
password : DBPASS,
),
reconnect : true,
timezone : $config['date_adjust'],
queryCache : true
),
],
]);
self::setConnection($dbConfig);
}
}
public static function getManager() : ORM\ORM {
if (is_null(self::$manager)) self::setManager();
return self::$manager;
}
public static function setManager(?ORM\ORM $manager = null, ?array $model_paths = []) : void {
if (!is_null($manager)) self::$manager = $manager;
else {
if (is_null(self::$manager)) {
$migrator = new Migrator($model_paths);
$registry = new Registry(self::getConnection());
$finder = new Finder();
$files = $finder->files()->in($migrator->getModelPaths());
$classLocator = new ClassLocator($files);
$embeddingLocator = new TokenizerEmbeddingLocator($classLocator);
$entityLocator = new TokenizerEntityLocator($classLocator);
$compiler = new Compiler();
$schemaArray = $compiler->compile($registry, [
new Schema\Generator\ResetTables(),
new Annotated\Embeddings($embeddingLocator),
new Annotated\Entities($entityLocator),
new Annotated\TableInheritance(),
new Annotated\MergeColumns(),
new Schema\Generator\GenerateRelations(),
new Schema\Generator\GenerateModifiers(),
new Schema\Generator\ValidateEntities(),
new Schema\Generator\RenderTables(),
new Schema\Generator\RenderRelations(),
new Schema\Generator\RenderModifiers(),
new Schema\Generator\ForeignKeys(),
new Annotated\MergeIndexes(),
new Schema\Generator\GenerateTypecast(),
]);
$schema = new Cycle\ORM\Schema($schemaArray);
$factory = new ORM\Factory(self::getConnection());
$container = new Container();
$commandGenerator = new EventDrivenCommandGenerator($schema, $container);
$orm = new ORM\ORM(
factory : $factory,
schema : $schema,
commandGenerator : $commandGenerator
);
$generator = new Cycle\Schema\Generator\Migrations\GenerateMigrations($migrator->getMigrator()->getRepository(), $migrator->getMigrator()->getConfig());
$generator->run($registry);
$migrator->runMigration();
$migrator->runMigration(true);
self::$manager = $orm;
}
}
}
/**
* @return DatabaseManager|null
*/
public static function getConnection() : ?DatabaseManager {
self::init();
return self::$connection;
}
/**
* @param Config\DatabaseConfig $config
*/
public static function setConnection(Config\DatabaseConfig $config) : void {
self::$connection = new DatabaseManager($config);
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
Migrator <?php
use Cycle\Migrations;
use Cycle\Migrations\Capsule;
use Cycle\Migrations\Config\MigrationConfig;
/**
* Класс для работы с миграциями
* Проверяет есть ли миграции для моделей базы данных
* Если такие есть, то выполняет миграции
*
* Создаёт так-же соединение к базе данных
*
* @since 171.3.0
*
* */
class Migrator {
/**
* Мигратор, который проверяет наличие новых миграций и выполняет их
*
* @var Migrations\Migrator|null
*/
private ?Migrations\Migrator $migrator = null;
/**
* Массив путей к моделям
*
* @var array
*/
private array $model_paths = array();
public function __construct(string|array|null $model_paths = null) {
global $mh_models_paths;
$this->setModelPaths($mh_models_paths);
if (!is_null($model_paths)) $this->setModelPaths($model_paths);
}
public function getModelPaths() : array {
return $this->model_paths ?? [];
}
/**
* Устанавливает пути к моделям
*
* @param array|string $model_paths Путь к моделям
*
* @return void
*/
public function setModelPaths(array|string $model_paths) : void {
if (is_array($model_paths)) {
$this->model_paths = array_merge($model_paths, $this->model_paths);
} else {
$this->model_paths[] = $model_paths;
}
foreach ($this->model_paths as $id => $model_path) {
$this->model_paths[$id] = DataManager::normalize_path($model_path);
}
}
public function runMigration(bool $user_db = false) : void {
$db = $user_db ? 'user' : 'default';
$this->getMigrator()->run(new Capsule(DbHandler::getConnection()->database($db)));
}
/**
* Создаёт / проверят наличие новых миграций с базой данных.
* Миграции хранятся по установленному пути
*
* @since 171.3.0
* @return Migrations\Migrator
*/
public function getMigrator() : Migrations\Migrator {
if (is_null($this->migrator)) {
$migratorConfig = new MigrationConfig([
'directory' => DataManager::normalize_path(MH_ROOT . '/_migrations/'),
'table' => 'maharder_migrations',
'safe' => true
]);
$migrator = new Migrations\Migrator($migratorConfig, DbHandler::getConnection(), new Migrations\FileRepository($migratorConfig));
$migrator->configure();
$this->migrator = $migrator;
}
return $this->migrator;
}
} |
Beta Was this translation helpful? Give feedback.
3 replies
-
paths.php <?php
if (!defined('DATALIFEENGINE')) {
header('HTTP/1.1 403 Forbidden');
header('Location: ../../../../../');
exit('Hacking attempt!');
}
$current_dir = __DIR__;
if (preg_grep('/(cache)/', explode("\n", $current_dir))) $current_dir = dirname(__FILE__, 5);
else $current_dir = dirname(__FILE__, 6);
if (!defined('ROOT')) {
define("ROOT", $current_dir);
}
if (!defined('MH_ROOT')) {
define("MH_ROOT", ROOT . '/engine/inc/maharder');
}
if (!defined('MH_ADMIN')) {
define("MH_ADMIN", MH_ROOT . '/admin');
}
$mh_models_paths = [
MH_ROOT . '/_models/Admin',
// Custom models //
];
$mh_loader_paths = [
MH_ROOT . '/_includes/classes',
MH_ROOT . '/_includes/classes/db',
MH_ROOT . '/_includes/database',
MH_ROOT . '/_includes/traits',
MH_ROOT . '/_includes/twigExtensions',
MH_ROOT . '/_models',
// Custom paths //
];
$mh_loader_paths = array_merge($mh_loader_paths, $mh_models_paths);
include_once MH_ROOT . '/_includes/extras/functions.php';
include_once MH_ROOT . '/_includes/extras/mhLoader.php';
include_once MH_ROOT . '/_includes/vendor/autoload.php';
ComposerAction::destroy(); |
Beta Was this translation helpful? Give feedback.
0 replies
-
mhLoader.php <?php
@ini_set('pcre.recursion_limit', 10000000);
@ini_set('pcre.backtrack_limit', 10000000);
@ini_set('pcre.jit', false);
spl_autoload_register(function ($class_name) {
global $mh_loader_paths;
$found = false;
foreach ($mh_loader_paths as $path) {
$dir_data = dirToArray($path);
foreach ($dir_data as $data) {
if ($class_name === str_replace('.php', '', $data)) {
include_once DLEPlugins::Check("{$path}/{$data}");
$found = true;
break;
}
}
if ($found) break;
}
}); |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
first of all my basics
db config -> calls with DbHandler::$connection
Migrator
ORM
Models path
my base model
actual model in model path
THe problem is that
new Annotated\Entities($entityLocator)
doesn't find the modelMhLog
. Maybe I got wrong the info from docsBeta Was this translation helpful? Give feedback.
All reactions