I know that in folder config are file called core.php which I can configure application options as a debug mode, session, cache etc.
But I want do configure file for my application. I want for example configure how many post can be displayed in main page, thubnails size etc.
I think that the best place in config folder but where and when parse thos file in application (bootstrap, AppController another mechanism ?) and what is the best extension .ini or PHP array (for performance reason too). What is the best practice to do this ?
DEFINE OWN CONSTANT FILE
Create a file lets suppose 'site_constants.php' containing some constant variables in app/Config folder. Define the following constants into it:
<?php
define('HTTP_HOST', "http://" . $_SERVER['HTTP_HOST'].'/');
if(HTTP_HOST == 'localhost' || HTTP_HOST == '127.0.0.1')
{
define('SITE_URL', HTTP_HOST.'app_folder_name/');
}
else
{
define('SITE_URL', HTTP_HOST);
}
Include it in app/Config/bootstrap.php
require_once('site_constants.php');
Now you can use it anywhere into your website. And this is also a dynamic.
DEFINE OWN CONFIGURATION FILE
Create a file lets suppose 'my_config.php' containing some constant variables in app/Config folder. Define the constant in the following way:
<?php
$config['PageConfig'] = array('PostPerPage' => 5, 'UserPerPage' => 15);
Then in your app/Controller/AppController.php write the following line in beforeFilter() method:
function beforeFilter()
{
Configure::load('my_config');
}
Now in your controller's method, where you want to access the page number to be listed in your pagination list. You can use it by following code:
$page_config = Configure :: read('PageConfig');
$user_per_page = $page_config['UserPerPage'];
//or
$post_per_page = $page_config['PostPerPage'];
This might looks long process to handle this task, but once done, it will help you in many senses.
Here are the advantages:
you can easily define some more constants (like any file path etc).
you can put all your ajax code into external JS files.
you can directly deploy it onto any server without changing in constants as well as work perfectly onto your localhost.
following standard conventions etc.
CakePHP provides the Configure class for this purpose. See the documentation.
You can use Configure::write($key,$value) in your own config file, and then read the values elsewhere in your application through Configure::read($key). It also allows you to use readers that automate the process and read in external configuration files. CakePHP provides a PHPreader and an INIreader by default and you can create readers to extend it.
Create a new file with configuring variables, like:
Configure::write('Twitter', array(
'consumer_key' => "OTh1sIsY0urC0n5um3rK3Y4T878676",
'consumer_secret' => "OTh1sIsY0ur53cReT76OTIMGjEhiWx94f3LV",
'oauth_access_token' => "12345678-OTh1sIsY0urAcc355K3YT878676Y723n4hqxSyI4",
'oauth_access_token_secret' => "OTh1sIsY0urACC355T0KEnsdjh4T878676FPtRRtjDA29ejYSn"
));
save this file in app/Config/twitter.php
Include that file in app/Config/bootsrap.php:
require_once('twitter.php');
In the Controller (this example 'app/Controller/TwitterController.php'), you can use that like:
$settings = Configure :: read('Twitter');
Related
This my data that I want to store my pdf files in my public folders. Anyone can give me any idea?
I tried to foreach the data to get that file but it seems not working in my end. Anyone can help me?
To store files in your public folder you can use the public disk that's included in your application's filesystems configuration file, the default config will store files in storage/app/public.
To make these files accessible from the web though (which I'm assuming is what you want) you need to create a symbolic link from public/storage to storage/app/public.
To do that just run:
php artisan storage:link
Once you've done this you can use Laravel's storage facade to interact with the files in your public folder to save, retrieve and download them.
Store
use Illuminate\Support\Facades\Storage;
Storage::put('file.jpg', $contents);
Download
return Storage::download('file.jpg');
return Storage::download('file.jpg', $name, $headers);
Retrieve
$contents = Storage::get('file.jpg');
If you need to store user uploaded files to your public storage, you can do it like this:
$path = $request->file('yourUploadedPdf')->store('yourPdfsFolder');
Laravel's store method will generate a unique ID for the filename and the extension will be determined by the MIME type of the uploaded file. The store method also returns the path, including the generated filename, so you can store it in your DB if needed.
If you need to specify the filename then you can do this:
$path = $request->file('pdf')->storeAs(
'yourPdfsFolder', 'yourPdfFileName'
);
Just a note, I'm assuming you'll be having public as your default disk, if not, then you'll need to specify the disk you're using in these method / Storage facade calls.
And a further note, when using the public disk, everything - by default - gets stored under storage/app/public so anytime you're defining a folder to store your uploaded PDFs under, it'll be storage/app/public/yourFolder.
In an unrelated, vanilla PHP project, I simply have this:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
It pulls in just fine. Following CakePHP 2.10's standards, I put all associated (composer'd) files in the app/Vendor folder and try this in my controller:
public function index($load = null) {
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
include(APP . 'Vendor' . DS.'autoload.php');
I get:
syntax error, unexpected 'use' (T_USE)
Any attempts to move the use around end up not working, so I ignore them and try to get it to work without namespaces.
require_once(APP . 'Vendor' . DS.'autoload.php');
require_once(APP . 'Vendor' . DS.'phpmailer\phpmailer\src\PHPMailer.php');
I know it's loading the PHP file via require_once, and that file includes the PHPMailer class. I get this error:
Error: Class 'PHPMailer' not found
But I know that class has to be present somewhere, because I loaded it. Code looks like this, to call it:
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.zoho.com'; // Specify main and backup SMTP servers
etc. So I'm not sure if this version of PHPMailer refuses to work without namespaces, which CakePHP 2 doesn't support? All other questions on Google do not seem to help me.
You're putting the use statements in the wrong place; they need to go at the top of your file (after any namespace declaration) as they are not block-scoped. Read the PHP docs.
You can mix namespaced and non-namespaced code, you just need to be aware that it's going on.
I'm still getting to grips with puppet (feels like I'm drinking from a hose pipe at times) so I've attempted to keep my configuration and environment simple initially. I've started by having puppet deploy files to my clients. However, I get the feeling that the way I'm deploying the files isn't the most efficient way of doing so. For every file, I'm specifying like this:
file { "/etc/ntp.conf":
owner => 'root',
group => 'root',
mode => '0444',
source => 'puppet://basxtststinfl01/files/etc/ntp.conf',
}
file { "/etc/snmp/snmpd.conf":
owner => 'root',
group => 'root',
mode => '0644',
source => 'puppet://basxtststinfl01/files/etc/snmpd.conf',
}
I have up 15 files I'd like to deploy. Is this the correct approach?
Thanks.
File in modules is a good keyword.
Generally, to solve the problem of repetitive resource, you can wrap them in a defined type.
define deployed_file($ensure = 'present',
$owner = 'root',
$group = 'root',
$mode = '644',
$recurse = '') {
if $recurse != '' { File { recurse => $recurse } }
file {
$name:
ensure => $ensure,
owner => $owner,
group => $group,
source => "puppet://basxtststinfl01/files${name}",
}
}
Your resources from above can then be written as:
deployed_file {
'/etc/ntp.conf':
mode => '444';
'/etc/snmp/snmpd.conf':
}
You can add more parameters to make the URL customizable.
Note that I added the recurse parameter for posterity. file has lots of attributes, and if you need for the deployed_file to support them, you should add them in this manner, so that they get passed to the wrapped file if specified, but ignored otherwise.
I suppose the question of whether this is the ‘correct approach’ comes down to what you’re doing exactly, but since ‘it depends’ is sometimes an annoying thing to hear, theres a few general points that can be made ...
This is an approach that will work - it would deploy the 15 or so files that you have declared exactly as you specify them.
It does however come at the expense of requiring the exact maintenance of your files as they are written in basxtststinfl01
Since these are static files, you might find it restrictive if you come to running puppet code to provision many different servers.
So to options! The examples you have given there can be considered from the context of puppet modules - reusable code to configure a particular service or logical unit of your system
In your ntp case, there is an ntp puppet labs module which contains logic within it to create an ntp.conf file and takes variables as parameters to configure it. This shortens the puppet declaration and allows you to reuse it for provisioning more servers. An example of how to configure this is given in the documentation of the puppetlabs-ntp module.
class { '::ntp':
servers => [ 'ntp1.corp.com', 'ntp2.corp.com' ],
}
More often that not, someone has written a module that will provision a part of the system that you want, see the Puppet Forge
Decomposing your system requirements into units and using modules means you can specify your config files dynamically according to variables that might vary from system to system.
Best thing to do is work through the excellent documentation on the puppetlabs website:
Some resources:
Learning Puppet (you may already have seen)
Basics of modules
I have a site running in localhost as a development environment and in a server for production.
There are some differences in some configuration files between both and I every time I have to update the changes in the server I have to be careful not to overwrite some files which are different.
I would like to be able to simplify this process by creating just one single file with the correct configuration for each environment.
I need to read that file currently in this Config files:
app/Config/email.php
app/Config/routes.php
And ideally, if possible in:
app/Vendor/Vendor_name/vendor_file.php
Is it possible somehow?
I have tried to use Configure::read and Configure::write but it seems it can not be done inside email settings such as public $smtp or in the routes file.
Thaks.
The routes file is simply a php file with calls to the router. You could very simply split it up into multiple files and load them yourself:
app/Config/
routes.php
routes_dev.php
routes_production.php
routes.php would then load the proper routes file.
<?php
if ($env == 'dev') {
include 'routes_dev.php';
} else {
include 'routes_production.php';
}
The email config is also just a php file. You could write a function to set the proper default config based on the environment.
class EmailConfig {
public function __construct() {
if ($env == 'dev') {
$this->default = $this->dev;
}
}
public $default = array(
'host' => 'mail.example.com',
'transport' => 'Smtp'
);
public $dev = array(
'host' => 'mail2.example.com',
'transport' => 'Smtp'
);
}
As for vendor files, that's a case by case basis.
If you have a deployment system, it might be better to actually have separate files for each environment (maybe even a full config directory) and rename them after the deployment build is complete, making Cake and your code none the wiser.
The way I used to handle this situation was to add environment variables to the apache virtualhost configuration.
SetEnv cake_apps_path /var/www/apps/
SetEnv cake_libs_path /var/www/libs/
This allowed me to then pull $_SERVER['cake_apps_path'] and $_SERVER['cake_libs_path']. Then each developer can set his own variables in his own virtualhost config, and you add that to the server's virtualhost config, and you're done. Each developer can have their own pathing.
I'm currently working with cakephp and I am generating a word document. My problem is how can I put the generated document on my web root and not as a download.
I am guessing you are using an action to generate a document, which gets output to the browser.
You should either use output buffering to "catch" the output and then write it to a file, or write the document data to a string, and write that string to a file on the server.
EDIT:
PHPWord has a SAVE method. In your action, you can save the document to a certain location, but output something else, i.e. success notification. This way, your action only generates the file:
public function generateWordDocument(){
//... your word file creation...
$wordDocumentLocation = TMP . 'word_files/';
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save($wordDocumentLocation . 'helloWorld.docx');
$this->Session->setFlash('Document generated!');
$this->redirect(array('action'=>'index')); //or wherever you want
}
If you want to protect that file, you could save the file to a "secure" folder (this can either be a folder outside the "app/webroot" folder, or a folder protected with .htaccess deny all instruction) and than use another action, like "getWordDocument":
function getWordDocument($documentName){
$wordDocumentLocation = TMP . 'word_files/';
if (file_exists($wordDocumentLocation . $documentName)) { //this is not really the safest way of doing it
$fp = fopen($wordDocumentLocation . $documentName, 'rb');
header("Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document");
header("Content-Length: " . filesize($wordDocumentLocation . $documentName));
fpassthru($fp);
exit();
}
}
Please note, that this code is just for "grasping the concept" and is in no way safe or optimal.
i think you want to add file in webroot but it is not downloadable for public users ,
You have several ways :
- protect folders with .htaccess (Like Js folder)
- create new folder in app folder like webroot and put files in it
- use Dispatcher Filters in cakephp : http://book.cakephp.org/2.0/en/development/dispatch-filters.html
and ....