Cakephp Plugin to generate sitemap - cakephp

I'm using Cakephp 2.4.3 . I've read that "There are CakePHP plugins that are able to generate sitemaps for you. This way your sitemap.xml file will be created dynamically on demand and will always be up to date." . I've searched but all I find are from old cakephp version which is not useful as they only cause errors .
Is there still a good plugin for this?

Some plugins definitely exist:
https://github.com/sdevore/cakephp-sitemap-plugin
https://github.com/smarek/Croogo-Sitemap-2.0
https://github.com/webtechnick/CakePHP-Seo-Plugin
Are these the old, error-causing ones? As each CakePHP site can be radically different to the next, I'm not sure a one-size-fits-all solution will exist.
If you end up writing your own sitemap implementation, it'll depend mainly on whether your site has:
Lots of database-driven content with few controllers/actions (like a typical WordPress-style site)
Lots of controller/action driven content (more of a web application)
In the first case, you'd want to perform finds on your content, and inject the results into an xml template like this: http://bakery.cakephp.org/articles/masterkeedu/2008/08/26/automatically-generate-dynamic-sitemaps
For the second case, the following may help: a component I've used for development/testing, which lists all controllers and their methods:
<?php //File: app/Controller/Component/CtrlComponent.php
// Component rewritten for Cake2.x, original from : http://cakebaker.42dh.com/2006/07/21/how-to-list-all-controllers/
class CtrlComponent extends Component {
/**
* Return an array of Controllers and their methods.
* The function will exclude ApplicationController methods
* #return array
*/
public function get() {
$aCtrlClasses = App::objects('controller');
foreach ($aCtrlClasses as $controller) {
if ($controller != 'AppController') {
// Load the controller
App::import('Controller', str_replace('Controller', '', $controller));
// Load its methods / actions
$aMethods = get_class_methods($controller);
foreach ($aMethods as $idx => $method) {
if ($method{0} == '_') {
unset($aMethods[$idx]);
}
}
// Load the ApplicationController (if there is one)
App::import('Controller', 'AppController');
$parentActions = get_class_methods('AppController');
$controllers[$controller] = array_diff($aMethods, $parentActions);
}
}
return $controllers;
}
}
In reality, a full sitemap probably uses both methods, and you'll need to consider the difference between public and "private" areas of your site (excluding admin prefixes, for example)..

Related

CakePHP How to create pagination from API JSON data source

I have an API like example
I have used cakephp HTTP client to get data, below my attempted code
public index()
{
$http = new Client();
$response = $http->get('https://restcountries.eu/rest/v2/all');
// $json = $response->getJson(); //also tried usgin json
$countries = $this->paginate($response);
$this->set(compact('countries '));
}
I am trying to apply pagination with this country data then fetch it in view with pagination.
After tried above code , I have gotten below error
Argument 1 passed to Cake\Datasource\Paginator::extractData() must be an instance of Cake\Datasource\RepositoryInterface, instance of Cake\Http\Client\Response given, called in \myapp\vendor\cakephp\cakephp\src\Datasource\Paginator.php on line 176
How can I get my desire result ?
You have probably need to implement a class who extend RepositoryInterface.
class JsonSource implements Cake\Datasource\RepositoryInterface
{ ... }
public index() {
$http = new Client();
$response = $http->get('https://restcountries.eu/rest/v2/all');
$src = new JsonSource();
$src->fromResponse($response);
$countries = $this->paginate($src);
$this->set(compact('countries ')); }
Is a bit tedious, because you need to define Json like a datasource.
The default pagination only supports querying tables (repositories), or operating on pre-built query instances.
To extend on #Zeppi's answer. You basically have three somewhat straightforward options here:
Create custom query/repository implementations as hinted by #Zeppi.
This can indeed be quite a lot of work though, so you might want to look into alternatively implementing it with the help of plugins, for example muffin/webservice, which does most of the hard work of implementing the required interfaces.
Or create a custom paginator that actually accepts and works on array data.
Or use what is widely know as a "datatable", that is a JavaScript based table in the frontend that paginates the data, for example jQuery DataTables.

Organize Models in subdirectories CakePHP 3

we are using subdirectories in our projects no separete views and controllers but in models we didn’t learn yet. Recently I’ve found this https://github.com/cakephp/cakephp/issues/60451 and actually routes and plugins we are already using, we just want to separete our models like this:
Model
-Entity
–Financial
—Money.php
-Table
–Financial
—MoneyTable.php
I’ve tryed put like this then controller is not able to find his model. How can I do to organize it, and make it work?
Things that we've tried:
Use $this->setAlias('TableModel');
Call in controller:
$this->TableModel = $this->loadModel('Subfolder/TableModel');
didn't work for SQL build, and other classes.
CakePHP uses the TableRegister to load models. That class can be configured to use a class that implements the LocatorInterface, and CakePHP uses the TableLocator as the default.
The only thing you can do is configure your own LocatorInterface instance in your bootstrap.php. You would have to create your MyTableLocator and have it change the className for tables to point to subdirectories. What rules for this class name rewritting are used is purely up to you.
bootstrap.php:
TableRegister::setTableLocator(new MyTableLocator());
MyTableLocator.php:
class MyTableLocator extends TableLocator {
protected function _getClassName($alias, array $options = [])
{
if($alias === 'Subfolder/TableModel') {
return TableModel::class;
}
return parent::_getClassName($alias, $options);
}
}
The above isn't working code.
I'm just demonstrating what the function is you need to override, and that you need logic in place to return a different class name.
You can check if the $alias contains the / character, and if so. Return a class name by extracting the subfolder name from the $alias. Take a look at the TableLocator to see how it's using the App::className function.

How to set up CakePHP 2.x to behave like a RESTful webservices (for using it together with JavascriptMVC)

I am trying to set up cakephp to work with the very nice javascriptMVC (http://forum.javascriptmvc.com). JavaScriptMVC requires the JSON-Output in the following format:
[{
'id': 1,
'name' : 'Justin Meyer',
'birthday': '1982-10-20'
},
{
'id': 2,
'name' : 'Brian Moschel',
'birthday': '1983-11-10'
}]
Cake would generate a deeper nested array with a prepended Class Name. I found attempts to solve the problem but theyre not for cakephp 2.x. I know that I can simply generate a new array and json_encode() it via php, but it would be nicer to include a function like this https://gist.github.com/1874366 and another one to deflatten it.
Where would be the best place to put such functions? The AppController doesnt seem to work. Should i put it in beforeRender () or beforeFilter() of the controller? Or does someone maybe even know of an existing solution/plugin for this? This would be the best for me in my current Situation, as Im pretty much pressed for time.
Ok, I'm not 100% sure I understand what you are trying to do so here's a word to the wise just in case: Cake and JMVC are both comprehensive MVC frameworks. if you are attempting to combine them as a single cohesive platform to build your application, I strongly suggest you review your approach / platform / etc.
Also -- I'm not an expert by any means in jmvc, so I'm just going to pretend that processing the response from Cake in jmvc is completely out of the question, for some odd reason. For the record, think of Cake's responses like this:
{ "Model" :
[{
'id': 1,
'name' : 'Justin Meyer',
'birthday': '1982-10-20'
},
{
'id': 2,
'name' : 'Brian Moschel',
'birthday': '1983-11-10'
}]
}
Cake has had comprehensive REST service support, since at least Cake 1.2. The lib you are interested in is HttpSocket. As for json encoding and serving response, Request Handling covers, among other things, responding to all manners of requests, content types, decoding and encoding json, etc. Finally, the built-in Set utility will almost certainly cover whatever array manipulation you need in a line or two.
The functionality you are interested in is pretty basic and hasn't changed too much. I'd bet a lot of the (reasonably simple) solutions you have already found would probably still work, maybe with a little bit of tweaking.
For pretty much any basic service endpoint, you would probably create a controller (not AppController - that is application-wide, hence you can't invoke it directly) method, considering Cake routes the controller/action into your url:
Cake consuming services from a different app would look like this:
http://cakeproject/collect/getInfo
class CollectController extends AppController {
public function getInfo($array = null) {
App::uses('HttpSocket', 'Network/Http');
$http = new HttpSocket();
$http->get('http://jmvcproject/controller/action', $array);
// ...etc.
}
Cake providing services from the same controller / action to a different app would simply be:
public function getInfo($array = null) {
$results = $this->Collect->find('all', $array);
// ...fetch the results
}
Or you could just loop over that array with foreach($this->data as $data) { ... to drop the class name. But if your data will include associated models, etc, Set is probably the most versatile and resilient solution.
Anyway, HTH

Adding a 1 to many file upload to CRUD

My app has sales listing functionality that will allow the user to add 1 or more photos for the product that they want to sell.
I'm attempting to use the upload/filestore_image of ATK with a Join table to create the relationship - my models:
class Model_Listing extends Model_Table {
public $entity_code='listing';
function init(){
parent::init();
$this->addField('name');
$this->addField('body')->type('text');
$this->addField('status');
$this->addField('showStatus')->calculated(true);
}
function calculate_showStatus(){
return ($this->status == 1) ? "Sold" : "For Sale" ;
}
}
class Model_listingimages extends Model_Table {
public $entity_code='listing_images';
function init(){
parent::init();
$this->addField('listing_id')->refModel('Model_Listing');
$this->addField('filestore_image_id')->refModel('Model_Filestore_Image');
}
}
In my page manager class I have added the file upload to the crud:
class page_manager extends Page {
function init(){
parent::init();
$tabs=$this->add('Tabs');
$s = $tabs->addTab('Sales')->add('CRUD');
$s->setModel('Listing',array('name','body','status'),array('name','status'));
if ($s->form) {
$f = $s->form;
$f->addField('upload','Add Photos')->setModel('Filestore_Image');
$f->add('FileGrid')->setModel('Filestore_Image');
}
}
}
My questions:
I am getting a "Unable to include FileGrid.php" error - I want the user to be able to see the images that they have uploaded and hoped that this would be the best way to do so - by adding the file grid to bottom of the form. - EDIT - ignore this question, I created a FileGrid class based on the code in the example link below - that fixed the issue.
How do I make the association between the CRUD form so that a submit will save the uploaded files and create entries in the join table?
I have installed the latest release of ATK4, added the 4 filestore tables to the db and referenced the following page in the documentation http://codepad.agiletoolkit.org/image
TIA
PG
By creating model based on Filestore_File
You need to specify a proper model. By proper I mean:
It must be extending Model_Filestore_File
It must have MasterField set to link it with your entry
In this case, however you must know the referenced ID when the images are being uploaded, so it won't work if you upload image before creating record. Just to give you idea the code would look
$mymodel=$this->add('Model_listingimages');
$mymodel->setMasterField('listing_id',$listing_id);
$upload_field->setModel($mymodel);
$upload_field->allowMultiple();
This way all the images uploaded through the field will automatically be associated with your listing. You will need to inherit model from Model_Filestore_File. The Model_Filestore_Image is a really great example which you can use. You should add related entity (join) and define fields in that table.
There is other way too:
By doing some extra work in linking images
When form is submitted, you can retrieve list of file IDs by simply getting them.
$form->get('add_photos')
Inside form submission handler you can perform some manual insertion into listingimages.
$form->onSubmit(function($form) uses($listing_id){
$photos = explode(',',$form->get('add_photos'));
$m=$form->add('Model_listingimages');
foreach($photos as $photo_id){
$m->unloadDdata()->set('listing_id',$listing_id)
->set('filestore_image_id',$photo_id)->update();
}
}); // I'm not sure if this will be called by CRUD, which has
// it's own form submit handler, but give it a try.
You must be careful, through, if you use global model inside the upload field without restrictions, then user can access or delete images uploaded by other users. If you use file model with MVCGrid you should see what files they can theoretically get access to. That's normal and that's why I recommend using the first method described above.
NOTE: you should not use spaces in file name, 2nd argument to addField, it breaks javascript.

CakePHP - select database config based on route or url?

I'm working on a small CakePHP application that is subject to the following constraint (awkward but out of my control): I need it to work on either of two identical databases, with the choice being based on URL. For example:
http://www.example.com/myapp/foo/action/param
http://www.example.com/myapp/bar/action/param
The first obvious solution is to have two identical CakePHP applications at myapp/foo and myapp/bar with different database configurations. This has a kludgy feel to it, though, so I'm trying to find an elegant way of creating a single application.
The approach I'm considering is this: Define routes such that myapp/foo and myapp/bar will be associated with the same controller. Then give my DATABASE_CONFIG class a constructor:
function __construct() {
$pathParts = explode('/', $_SERVER['REQUEST_URI']);
if (array_search('foo', $pathParts)) {
$this->default = $this->fooConfig;
} else if (array_search('bar', $pathParts)) {
$this->default = $this->barConfig;
}
}
(Where of course I've defined fooConfig and barConfig for the two databases.) I do have control over the URL, so I can be confident that there won't be extraneous occurrences of foo or bar in the URL.
My question is this: Is there a simpler, more elegant way of handling this odd situation? Maybe something in AppModel and/or AppController? Although I'm getting rid of duplicated code, I can't shake the feeling that I'm replacing one code smell with another.
There are a few ways to do this, here is one.
Write a sweet custom route in which you always match:
Router::connect('/:ds/*', array(), array('routeClass' => 'SweetDbRoute'));
Then have SweetDbRoutes set a class variable you can use everywhere, including in your model constructors. Then it should fail so you don't actually adjust the request.
App::import('SweetDbClass', array('file' => '/path/to/your/sweet_db_class.php'));
class SweetDbRoute extends CakeRoute {
// put your failing route code here, but use your SweetDbClass to track datasource ...
// see http://book.cakephp.org/view/1634/Custom-Route-classes
}
Then in your AppModel:
App::import('SweetDbClass', array('file' => '/path/to/your/sweet_db_class.php'));
class AppModel extends Model {
public function __construct($id = false, $table = null, $ds = null) {
$ds = SweetDbClass::$ds;
parent::__construct($id, $table, $ds);
}
}
So for example, after you perform an insert in one database, the two won't be "identical", right? Are these 2 DB somehow synced with each other? I don't know what do you need to do on those DB, but it's probably easier just to do 2 separate apps.
Yes, you can specify the DB configuration in the model: http://book.cakephp.org/view/922/Database-Configuration but you can't change it on-the-fly though (the models are not expected to change association to another table, I suppose). What you do is probably the only way.
I do have control over the URL, so I can be confident that there won't be extraneous occurrences of foo or bar in the URL
Yes, there can be "extraneous occurrences of foo or bar in the URL" :)) But it won't break your app.

Resources